Go by Example: Building CLI Tools with Cobra
Go 1.23
Build professional-grade CLI applications using Cobra. This example introduces the Cobra library, used by projects like Kubernetes, showing how to define commands, subcommands, and flags with automatic help generation.
Code
package main
import (
"fmt"
"github.com/spf13/cobra"
"os"
)
func main() {
var rootCmd = &cobra.Command{
Use: "app",
Short: "My awesome CLI app",
Long: "This is a longer description of my awesome CLI app built with Cobra.",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello from the root command!")
},
}
var echoCmd = &cobra.Command{
Use: "echo [string to echo]",
Short: "Echoes the input",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Echo:", args[0])
},
}
rootCmd.AddCommand(echoCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}Explanation
Cobra is the industry-standard library for building modern CLI applications in Go, used by Kubernetes, Hugo, and the GitHub CLI. It provides a structured way to create commands, subcommands, and flags, along with automatic help generation and shell completion.
Cobra applications are built around three concepts:
- Commands: Represent actions (e.g.,
git commit). They are the central building blocks. - Args: The things being manipulated (e.g., filenames). Cobra provides built-in validators like
MinimumNArgs(1). - Flags: Modifiers for actions (e.g.,
--force). Cobra uses thepflaglibrary, which is POSIX-compliant (supporting--longand-sflags).
Code Breakdown
10-13
Defining the root command, which is the entry point of the application. Use is the command name, Short is a brief description shown in help, Long is a detailed description, and Run is the function executed when the command is called.
19-24
Defining a subcommand 'echo'. The Args field specifies argument validation - cobra.MinimumNArgs(1) ensures at least one argument is provided. If validation fails, Cobra automatically shows an error and usage information.
26
Adding the echo command as a child of the root command. This creates a command hierarchy where users run "app echo [args]".
28-31
Executing the root command. Execute() parses os.Args, finds the appropriate command, validates arguments, and runs the command's Run function. It returns an error if anything goes wrong.

