REST
How to develop a RESTful client in Go
Learn how to develop a command-line client to access a RESTful server in Go with Mihalis Tsoukalos and the Cobra library.
OUR EXPERT
Mihalis Tsoukalos is a systems engineer and technical writer. He’s the author of Go Systems Programming and Mastering Go. You can reach him at @mactsouk.
Part Two!
Did you miss part one? See page 66 to get hold of it!
T he subject of this month’s tutorial is RESTful services. In particular, you’re going to learn how to develop a client for an existing RESTful server using the Go programming language. The client is going to be able to communicate with the RESTful server that we developed in part one (see LXF282), which means that the command line utility must support all server endpoints. Let’s get started.
The supported REST API
First, let’s recap what our REST API client needs to support. The REST API is defined on the server side, but remember that you don’t have to support all endpoints. What is important is to use the correct endpoints along with the expected HTTP methods and JSON records. Once again, we need to marshal and unmarshal JSON data when interacting with the RESTful server. However, we’re not going to discuss the JSON marshalling and unmarshalling process in this tutorial – if you don’t know how to do this, get hold of the previous tutorial.
As a reminder, the REST API that we need to support includes four endpoints. These endpoints are /time (GET HTTP method), /insert (POST HTTP method), /delete (DELETE HTTP method) and /list (GET HTTP method). Only /insert requires JSON input whereas /list returns an array of JSON records instead of single JSON records. Additionally, /delete requires user input to know the username that’s going to be deleted, if it can be found in the server “database”.
Utility structure
We’re using cobra, which is a Go package that’s not part of the standard Go library. The development of the command line utility is going to take place under ~/go/ src. More specifically, under ~/go/src/restclient. First of all, we have to create the structure of the command line utility using the ~/go/bin/cobra utility:
$ cd ~/go/src/restclient
$ ~/go/bin/cobra init --pkg-name restclient
$ ~/go/bin/cobra add time
$ ~/go/bin/cobra add insert
$ ~/go/bin/cobra add list
$ ~/go/bin/cobra add delete
QUICK TIP
If you want your programs to validate JSON input according to some userspecified rules, check out the Go validator package at https://github. com/goplayground/ validator.
The second command is for initialising the cobra project. The remaining commands are for creating the desired utility commands. So, the restclient utility needs to support the insert , delete , list and time commands. After these cobra commands, the structure and the files of the utility, as presented by tree, are going to be as follows: . |—— LICENSE |—— cmd