Creating a Client for the Phone Book Service
Let’s create a client for the phone book web service using the cobra package.
We'll cover the following...
In this lesson, we create a command-line utility that interacts with the phone book web service that was developed earlier in this chapter. This version of the phone book client is going to be created using the cobra
package, which means that a dedicated GitHub or GitLab repository is required. In this case, the repository can be found here. The first thing to do after running git clone
is associating that repository with the directory that is going to be used for development:
# cd ~/go/src/github.com/Educative-Content# git clone https://github.com/Educative-Content/phone-cli# cd phone-cli# ~/go/bin/cobra init --pkg-name github.com/Educative-Content/phone-cli# go mod init# go mod tidy# go mod download
Next, we have to create the commands for the utility. The structure of the utility is implemented using the next cobra
commands:
# ~/go/bin/cobra add search# ~/go/bin/cobra add insert# ~/go/bin/cobra add delete# ~/go/bin/cobra add status# ~/go/bin/cobra add list
So, we have a command-line utility with five commands named search
, insert
, delete
, status
, and list
. After that, we need to implement the commands and define their local parameters in order to interact with the phone book server.
Coding example
Now, let’s see the implementations of the commands, starting from the implementation of the init()
function of the root.go
file because this is where the global command-line parameters are defined:
func init() {rootCmd.PersistentFlags().StringP("server", "S", "localhost", "Server")rootCmd.PersistentFlags().StringP("port", "P", "1234", "Port number")viper.BindPFlag("server", rootCmd.PersistentFlags().Lookup("server"))viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port"))}