Creating a RESTful client is much easier than programming a server mainly because we do not have to work with the database on the client side. The only thing that the client needs to do is send the right amount and kind of data to the server and receive back the server response. The RESTful client is going to be developed in ~/go/src/github.com/Educative-Content/rest-cli—if we do not plan to make it available to the world, we do not need to create a separate GitHub repository for it. However, for us to be able to see the code of the client, We created a GitHub repository, which is https://github.com/Educative-Content/rest-cli.

The supported first-level cobra commands are the following:

  • list: This command accesses the /getall endpoint and returns the list of users.

  • time: This command is for visiting the /time endpoint.

  • update: This command is for updating user records—the user ID can’t change.

  • logged: This command lists all logged-in users.

  • delete: This command deletes an existing user.

  • login: This command is for logging in a user.

  • logout: This command is for logging out a user.

  • add: This command is for adding a new user to the system.

  • getid: This command returns the ID of a user, identified by their username.

  • search: This command displays information about a given user, identified by their ID.

Note: A client like the one we are about to present is much better than working with curl(1) because it can process the received information but, most importantly, it can interpret the HTTP return codes and preprocess data before sending it to the server. The price we pay is the extra time needed for developing and debugging the RESTful client

There exist two main command-line flags for passing the username and the password of the user issuing the command: user and pass. Because we are going to see in their implementations, they have the -u and -p shortcuts, respectively. Additionally, because the JSON record that holds user info has a small number of fields, all the fields are going to be given in a JSON record as plain text, using the data flag and -d shortcut—this is implemented in root.go. Each command is going to read the desired flags only and the desired fields of the input JSON record—this is implemented in the source code file of each command. Lastly, the utility is going to return JSON records, when this makes sense or a text message related to the endpoint that was visited. Now, let us continue with the structure of the client and the implementation of the commands.

Creating the structure of the command-line client

This lesson uses the cobra utility to create a structure for the command-line utility. But first we are going to create a proper cobra project and Go module:

Get hands-on with 1400+ tech skills courses.