Build Your Own Powerful Modern CLI in Golang

As a Golang developer, the first thing you might have done is to run the go program from the command line. Have you ever thought of making one such modern command line interface? Recently I used the cobra library to develop such a command line interface. In this blog, I will walk you through an easy-to-follow example to develop your own command line interface.

Command-Line applications may not be common for general users. But it is used by developers, data scientists, system administrators, and other software professionals. Every command-line app needs a user-friendly command-line interface (CLI) so that you can interact with the app itself.

laptop, notebook, cellphone-1839876.jpg

What is CLI?

The command line interface is the text-based user interface, where the user gives commands to the computer by text. Generally, we use a Graphical user interface(GUI), where you provide the command to the computer by clicking or entering on the screen or pressing enter button. GUI might be easier to use, but it takes time and resources. If your user is technically sound, you can always choose to develop a user-friendly CLI application. User-friendly CLI makes it really intuitive for others to use your program. CLI development is faster and solves the purpose.

CLI is used in many applications like docker, Kubernetes, GitHub, npm, and go.

Today we will learn how can we create our own CLI application.

Golang for CLI

Golang is a great choice for developing CLI because it lacks deployment dependencies by compiling to a static binary.

Golang has libraries like cobra and cobra-cli, which will help you to write code faster and in a maintainable way. If you are familiar with Golang, you can even finish developing your first CLI in less than 30 minutes. Even if you are not familiar with Golang, it is quite easy to develop CLI in golang with the help of libraries.

What Are You Building Today?

Today you will be building a calculator which can do addition and multiplication only. It will take the first argument as the operation and the “number” as flags on which you provide. Don’t worry, you need not to remember any of these things to use it. You can use –help flag anytime ­čÖé

Your final CLI command will look like this:

calculator sum --number 10 --number 20
calculator prod  --number 20 --number 40

This CLI will provide:

  1. Intelligent suggestions
  2. Automatic help flag recognition of -h--help, etc.
  3. The flexibility to define your own help, usage, etc

and many more. You can read the complete list from the cobra readme section.

Libraries used

Cobra:

Cobra is a library for creating powerful modern CLI applications.

Cobra is a CLI library for Go that empowers applications. Let’s use this to make your modern powerful CLI.

Cobra-CLI Generator:

It is a very powerful application that will populate your program with the right structure so you can immediately enjoy all the benefits of Cobra. It produces all boilerplate code. This application is a tool to generate the needed files to quickly create a Cobra application.

Concepts

Few concepts which will help you to understand this tutorial better

Cobra is built on a structure of

  1. commands: Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children’s commands and optionally run an action. In the above example, ‘sum’ and ‘prod’ are the command
  2. Flags: A flag is a way to modify the behavior of a command. In the above example ‘number’ is the flag. In Cobra you can assign a flag in two ways:
    • Persistence Flag: Flags that are available for commands and commands under it.
    • Local flags: Flags can only be used by commands in which it is defined.

In the above example, we don’t have commands under commands, so you can use any type of flag. I will be using persistence flags for the example.

Set up your go Module

If you are setting up your go code the first time, you can refer to the go documentation.

For setting up the go module you can go to your GOPATH/src directory. Create a new folder named calculator. Since I am pushing the module to be used by others, I will be using the path of my public git. You should edit it according to your git path.

cd GOPATH/src
mkdir calculator && cd calculator
go mod init github.com/puru2901is/calculator  // provide your public git repo 

this will create go.mod file in the directory

Set cobra CLI Generator

This is will something really cool. When I first wrote the code for cobra, I wrote it without CLI generator. It took me a lot of time. You can save time by using this generator. This will produce the boilerplate code for you.

go install github.com/spf13/cobra-cli@latest

This will install cobra cli on $GOPATH/bin directory which should be in your $PATH. The following command will help in creating barebones for your project.

cobra-cli init

this will create a cmd folder, main.go, and LICENSE file in your folder

Now run

go run main.go

Output

A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.

Add commands simply by running these commands

cobra-cli add prod
cobra-cli add sum

this will create prod.go and sum.go in the cmd folder.

Time to write logic

Now all the boilerplate code is generated. You can change the ‘short’ and ‘long’ descriptions according to your need in the sum.go and the prod.go file. The sample will look like this.

Use:   "prod",
Short: "Product of the Numbers",
Long: `This command is used for product of numbers. You can provide more than one number flag in this command. Flags are complusory. For Example:
	calculator prod  --number 20 --number 40 
	output: 800
	calculator prod  --number 2 --number 4 --number 5
	output: 40`

Time to write the logic. You can have to look at the final CLI command written above in the blog. Our CLI command can take many ‘number’ flags. So you can use slice to store those flags. You will add this code in init method of the root.go

rootCmd.PersistentFlags().Float32SliceP("number", "n", []float32{}, "enter number(required)")

for the sum you will add this logic in Run of the sum.go

func(cmd *cobra.Command, args []string) {
var sum float64
numbers, _ := cmd.Flags().GetFloat32Slice("number")
for _, j := range numbers {
sum += float64(j)
}
fmt.Println(sum)
},

for the product of numbers you will add this logic in Run of the prod.go

func(cmd *cobra.Command, args []string) {
var sum float64
numbers, _ := cmd.Flags().GetFloat32Slice("number")
for _, j := range numbers {
//fmt.Println(i)
sum += float64(j)
}
fmt.Println(sum)
},

After all the changes you can run your code like

go run main.go  sum --number 10 --number 20

The last piece left is to run it directly with the ‘calculator’ keyword instead of ‘go run main.go’. Run

go install

This command will generate an executable ‘calculator’ in your $GOBIN folder. Set your PATH. Now you can run your calculator executable directly.

calculator sum --help
This command is used for product of numbers. You can provide more than one number flag in this command. Flags are compulsory. For Example:
calculator sum --number 20 --number 40
output: 60
calculator sum --number 2 --number 4 --number 5
output: 11
Usage:
calculator sum [flags]
Flags:
-h, --help help for sum
Global Flags:
-n, --number float32Slice enter number(required) (default [])

Hooray!!!

Distribution

Now push your code to a public GitHub repo and share your repo with your team so that they can also use your calculator.

For example, you can run this command it will install the calculator from my repo. You can also use this calculator.

go install github/puru2901/calculator

Congratulations on building your first CLI application. Check out the complete code on GitHub.

Conclusion

Golang cobra provides a powerfully modern tool for creating CLI. Golang and its libraries make CLI development really easy. So if you want to create CLI for you or your team which is intuitive to use, definitely consider Golang Cobra. Hope you enjoyed this blog.

Happy Coding!!!

Reference:

https://github.com/spf13/cobra/issues/661

https://github.com/spf13/cobra/blob/main/user_guide.md

https://github.com/spf13/cobra-cli/blob/main/README.md

https://go.dev/doc/gopath_code#GOPATH

This Post Has 3 Comments

  1. Registrácia

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

Leave a Reply