Building a Professional Go CLI with Cobra and Viper: Subcommands, Config, and Auto-Completion

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

The Problem: Why Quick-and-Dirty CLI Scripts Break Down

Every internal developer tool starts small. You write a 150-line Go binary with the standard flag package, hardcode two environment variables, and hand it to your team. Six months later, that little binary has snowballed into a core workflow tool with 12 subcommands, three environments, and 20 flags.

That is when the cracks show. Flag names drift across subcommands, environment variables clobber config files without warning, and teammates ping you on Slack because the help text is stale. Writing a custom parser from scratch is a waste of time. Pairing Cobra for command routing with Viper for layered configuration solves these problems right from the start.

Here are the exact patterns I use whenever I spin up a new Go CLI.

Core Concepts: How Cobra and Viper Fit Together

Before writing any Go code, draw a clear boundary between the two libraries so they do not step on each other.

Cobra: Command Tree and Flag Scoping

Cobra models your CLI as a tree. Everything hangs off a single rootCmd as child commands—think mycli deploy or mycli config view. Two flag scopes do most of the heavy lifting:

  • Persistent Flags: Attached to a parent command and inherited by every subcommand below it. Use these for global options like --config, --verbose, or --env.
  • Local Flags: Scoped to one specific command, such as --dry-run on a deploy command.

Viper: Layered Configuration Precedence

Viper decides where each setting comes from. Its main advantage is a strict precedence order, from highest priority to lowest:

  1. Explicit command-line flags
  2. Environment variables
  3. Configuration file (YAML, JSON, or TOML)
  4. Default values

One rule saves a lot of headaches: never call os.Getenv() inside your business logic. Let Viper resolve every setting in one place so your command handlers stay clean and easy to test.

Built-in Shell Auto-Completion

A CLI feels half-baked when Tab does nothing. Modern Cobra releases ship a built-in completion subcommand for Bash, Zsh, Fish, and PowerShell, along with hooks for dynamic argument suggestions.

Hands-on Practice: Tips and Patterns That Work

Let’s put together a minimal, production-ready layout. Start by creating a Go module and pulling in both dependencies:

mkdir mycli && cd mycli
go mod init github.com/example/mycli
go get github.com/spf13/cobra@latest github.com/spf13/viper@latest

1. Keep Your Root Command Thin and Use RunE

Many Go developers put logic inside Run and call os.Exit(1) on failure. Prefer RunE instead, which returns an error. Returning errors to main() keeps unit tests from crashing the test runner, and setting SilenceUsage: true stops Cobra from printing the entire help screen on runtime failures.

Inside cmd/root.go, hook into PersistentPreRunE so Viper initializes right before any subcommand runs:

package cmd

import (
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

var rootCmd = &cobra.Command{
	Use:          "mycli",
	Short:        "A reliable deployment and ops CLI",
	SilenceUsage: true,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		return initConfig(cmd)
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.mycli.yaml)")
	rootCmd.PersistentFlags().String("env", "dev", "target environment (dev, staging, prod)")
	rootCmd.PersistentFlags().BoolP("verbose", "v", false, "enable verbose logging")
}

2. Bind Flags and Environment Variables Cleanly

Flag binding trips up a lot of Cobra and Viper newcomers. If two subcommands define a local flag with the same name—say --timeout—and you bind both during init(), the second binding overwrites the first. Binding inside PersistentPreRunE fixes that collision because only the active command’s flags are bound.

While you are there, add an environment key replacer so kebab-case flags like --dry-run map cleanly to MYCLI_DRY_RUN:

func initConfig(cmd *cobra.Command) error {
	v := viper.GetViper()

	if cfgFile != "" {
		v.SetConfigFile(cfgFile)
	} else {
		home, err := os.UserHomeDir()
		if err != nil {
			return err
		}
		v.AddConfigPath(home)
		v.SetConfigName(".mycli")
		v.SetConfigType("yaml")
	}

	v.SetEnvPrefix("MYCLI")
	v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
	v.AutomaticEnv()

	if err := v.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			return fmt.Errorf("failed to read config: %w", err)
		}
	}

	// Bind both persistent and local flags of the active command
	return v.BindPFlags(cmd.Flags())
}

With this in place, local dev and CI pipelines stay completely separate. Engineers keep defaults in ~/.mycli.yaml, CI sets MYCLI_ENV=prod, and anyone can still pass --env staging for a quick one-off run.

3. Design Focused, Predictable Subcommands

Give each subcommand its own file under cmd/, like cmd/deploy.go. Validate positional arguments with built-in helpers such as cobra.ExactArgs(1) so bad input fails in under a millisecond—long before any API call fires.

package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var deployCmd = &cobra.Command{
	Use:   "deploy <service>",
	Short: "Deploy a service to the target environment",
	Args:  cobra.ExactArgs(1),
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) != 0 {
			return nil, cobra.ShellCompDirectiveNoFileComp
		}
		return []string{"api", "worker", "billing"}, cobra.ShellCompDirectiveNoFileComp
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		service := args[0]
		env := viper.GetString("env")
		dryRun := viper.GetBool("dry-run")

		fmt.Printf("Deploying %s to %s (dry-run=%v)\n", service, env, dryRun)
		return nil
	},
}

func init() {
	deployCmd.Flags().Bool("dry-run", false, "preview changes without applying them")
	rootCmd.AddCommand(deployCmd)
}

Look at ValidArgsFunction on deployCmd. Those six lines give users instant tab completion for valid service names right at the prompt.

4. Enable Shell Auto-Completion for Users

Cobra generates the completion subcommand out of the box, so you do not need any shell-specific boilerplate. Drop these setup snippets into your README so teammates can turn on tab completion in under 30 seconds:

# Bash (current session; requires bash-completion v2)
source <(mycli completion bash)

# Zsh (persist across sessions)
mycli completion zsh > "${fpath[1]}/_mycli"

# Fish
mycli completion fish | source

Running inside CI containers where nobody presses Tab? Set rootCmd.CompletionOptions.HiddenDefaultCmd = true to hide the command from help output without disabling it.

Conclusion: Keep Your CLI Predictable

Good CLI tools feel obvious because they follow conventions developers already expect. Cobra gives you a clean command tree, Viper enforces a single config hierarchy, and built-in shell completion removes guesswork at the terminal.

On your next Go CLI, stick to three habits: return errors with RunE, bind flags inside PersistentPreRunE, and wire up ValidArgsFunction on your main subcommands. That small upfront structure will hold up even when the tool doubles in size.

Share: