Building a CLI Application in Go with Cobra: A Step‑by‑Step Tutorial
This tutorial explains how to create a command‑line interface (CLI) application in Go using the Cobra library, covering project initialization, command and flag definitions, configuration handling with Viper, and extending the tool with sub‑commands for integer, floating‑point, and even‑number calculations.
Although most modern software provides graphical interfaces, command‑line tools remain essential for developers, and Go is an excellent language for building them. This guide demonstrates how to construct a CLI application using the popular Cobra library, which powers projects such as Kubernetes, Docker, and Hugo.
Concept
Cobra organizes a CLI around Commands , Args , and Flags . A basic command line looks like $ APPNAME Command Args -- Flags .
Project Setup
Create a directory, initialize a Go module, and install Cobra:
$ mkdir my-calc && cd my-calc
$ go mod init my-calc
$ go get -u github.com/spf13/cobra@latest
$ cobra init --pkg-name my-calcThe generated main.go calls cmd.Execute() , which runs the root command.
Root Command
The root command ( rootCmd ) is defined in cmd/root.go . Its Run function prints Hello Cobra CLI . Initialization functions ( init and initConfig ) set up configuration handling with Viper , reading a file named .my-calc from the user's home directory.
Adding Sub‑Commands
Use cobra add <commandName> to generate new commands. For example, cobra add add creates cmd/add.go with an addCmd variable. The Run function is replaced by a call to intAdd(args) , which sums integer arguments.
func intAdd(args []string) {
var sum int
for _, ival := range args {
temp, err := strconv.Atoi(ival)
if err != nil { panic(err) }
sum += temp
}
fmt.Printf("Addition of numbers %s is %d\n", args, sum)
}Running ./my-calc add 1 2 3 outputs Addition of numbers [1 2 3] is 6 .
Floating‑Point Support
A boolean flag --float (short -f ) is added to addCmd . When set, the command calls floatAdd(args) , which parses arguments with strconv.ParseFloat and prints the sum as a floating‑point number.
func floatAdd(args []string) {
var sum float64
for _, fval := range args {
temp, err := strconv.ParseFloat(fval, 64)
if err != nil { panic(err) }
sum += temp
}
fmt.Printf("Sum of floating numbers %s is %f\n", args, sum)
}Example: ./my-calc add 1 2 3.5 -f prints Sum of floating numbers [1 2 3.5] is 6.500000 .
Even‑Number Sub‑Command
A new sub‑command even is added under addCmd using cobra add even . Its Run function sums only even integers from the arguments.
func Run(cmd *cobra.Command, args []string) {
var evenSum int
for _, ival := range args {
temp, _ := strconv.Atoi(ival)
if temp%2 == 0 { evenSum += temp }
}
fmt.Printf("The even addition of %s is %d\n", args, evenSum)
}Running ./my-calc add even 1 2 3 4 5 6 yields The even addition of [1 2 3 4 5 6] is 12 .
Conclusion
By following these steps you can build a functional Go CLI application with Cobra, manage configuration via Viper, and extend the tool with custom commands and flags for various calculation scenarios.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.