Skip to content

Advanced CLI with cobra and viper

For production‑grade CLI tools, use cobra (commands, subcommands, help) and viper (configuration from flags, env, files). Cobra is used by Kubernetes, Docker, GitHub CLI, etc.

A simple cobra app with one command.

package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var name string
rootCmd := &cobra.Command{
Use: "greet",
Short: "Greets someone",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", name)
},
}
rootCmd.Flags().StringVarP(&name, "name", "n", "World", "Name to greet")
rootCmd.Execute()
}
Terminal window
Hello, Alice!