ThisCalculator

Everyday

Go CLI with Cobra and Config Management

Updated · Standard formula, shown below

Building a Go command-line tool with Cobra and configuration management means using the Cobra library for command-line parsing and a separate approach (like Viper, environment variables, or JSON/YAML files) for handling settings. This article explains how to structure such a tool, choose a configuration strategy, and avoid common pitfalls.

Why Cobra for CLI Structure

Cobra is a popular Go library for creating modern CLI applications. It provides a framework for defining commands, subcommands, and flags, and it automatically generates help text and shell completion scripts. Cobra is used by many well-known projects, including Kubernetes and Hugo, which speaks to its robustness and community adoption.

The core concept is a root command that can have nested subcommands, each with its own set of flags and arguments. For example, a tool named app might have app serve and app config subcommands. Cobra handles the routing of inputs to the correct command, and it also supports persistent flags (available to all subcommands) and local flags (only for one command).

Configuration Management Options

Configuration management is about how your tool reads settings that can change between environments or user preferences. In Go, there are several common approaches:

  • Environment variables: Simple, language-agnostic, and widely supported. Use the os.Getenv function or a library like godotenv to load a .env file.
  • Configuration files: JSON, YAML, TOML files that the user can edit. Libraries like viper (from the same author as Cobra) can read these formats and also merge with environment variables.
  • Command-line flags: For values that change frequently, flags are the most direct. Cobra integrates with the standard flag package or pflag (which Cobra uses).
  • Combination: A typical pattern is to have defaults, then a config file, then environment variables, then flags, with each overriding the previous. Viper supports this precedence natively.

Setting Up a Cobra Project

To start, you need to initialize a Go module and add Cobra as a dependency:

go mod init mycli
go get github.com/spf13/cobra

Create a file, say main.go, and define a root command:

package main

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:   "mycli",
    Short: "A brief description of your application",
    Long:  `A longer description that spans multiple lines.`,
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("Hello from mycli")
    },
}

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

Then you can add subcommands by creating new cobra.Command objects and adding them to the root with rootCmd.AddCommand(subCmd). Each subcommand can have its own Run function and flags.

Integrating Configuration with Viper

Viper is a companion library to Cobra that handles configuration. It can read from a file, environment variables, and remote key-value stores (like etcd). The typical setup is to initialize Viper in an init function or in the command’s PreRun hook.

import "github.com/spf13/viper"

func init() {
    viper.SetConfigName("config") // name of config file (without extension)
    viper.SetConfigType("yaml")   // REQUIRED if the config file does not have the extension
    viper.AddConfigPath(".")      // look for config in the working directory
    viper.AutomaticEnv()           // read in environment variables that match

    if err := viper.ReadInConfig(); err != nil {
        // It's okay if there's no config file; we'll use defaults.
    }
}

Then you can access values with viper.GetString("key"), viper.GetInt("port"), etc. You can also set defaults with viper.SetDefault("port", 8080).

Common Pitfalls and How to Avoid Them

  • Ignoring the order of precedence: If you read a config file after setting defaults, the file will override defaults. But if you read flags after that, flags should override the file. Make sure you bind flags to Viper keys and call viper.BindPFlag to get the correct precedence.
  • Not handling missing config gracefully: Your tool should work with sensible defaults if no config file is present. Use viper.ReadInConfig() and ignore the error if it’s a ConfigFileNotFoundError.
  • Overcomplicating with too many config sources: Sometimes a simple JSON file and a few flags are enough. Adding environment variables can be useful for CI/CD, but it can also make testing harder.
  • Not validating configuration: If a config value is invalid (e.g., a negative port), your tool should fail with a clear message. Use a library like go-playground/validator or manual checks.

Comparing Cobra to Other CLI Libraries

Cobra is not the only option. The standard library flag package is simple but lacks subcommands and advanced features. urfave/cli is another popular library that provides a similar API but with a different style. kong is a more declarative approach using struct tags. Cobra stands out because of its integration with Viper, its support for shell completion, and its widespread adoption, which means more examples and community support.

Best Practices for Configuration in CLI Tools

  • Use a consistent naming convention: For environment variables, use a prefix like MYAPP_ to avoid collisions. For config file keys, use lowercase with hyphens or underscores.
  • Document all configuration options: Provide a sample config file and explain each key in your README.
  • Allow overrides for testing: Make it easy to change config in tests, for example by using a function that returns the config struct rather than a global.
  • Cache configuration reads: If you read a config file many times, consider loading it once into a struct.

Frequently Asked Questions

How do I make a flag override a config file value?

Use Viper’s BindPFlag to bind a flag to a Viper key. For example, if you have a flag --port, you can do viper.BindPFlag("port", cmd.Flags().Lookup("port")). Then Viper will automatically use the flag value if it is set, otherwise it will fall back to the config file or default.

Should I use JSON or YAML for my config file?

Both are fine. JSON is built into Go and has no external dependencies, but it doesn’t support comments. YAML is more human-friendly and supports comments, but requires a third-party library (like gopkg.in/yaml.v3). If you use Viper, it supports both, so choose based on your audience.

Can I use Cobra without Viper?

Yes, Cobra works independently. You can use the standard flag package or pflag directly. Viper is optional, but it simplifies configuration management.

How do I add shell completion to my Cobra CLI?

Cobra has built-in support for generating shell completion scripts. You can add a completion command to your root command with rootCmd.AddCommand(&cobra.Command{Use: "completion", ...}) and use the GenBashCompletion, GenZshCompletion, etc. functions. The generated scripts can be sourced by the user.

What is the best way to handle config file paths?

Allow the user to specify a config file path with a flag like --config, and also search in common locations like the current directory, $HOME/.config/myapp/, and /etc/myapp/. Use Viper’s AddConfigPath to add multiple paths.

Is it safe to store secrets in config files?

Generally no. Config files are often committed to version control. Use environment variables or a secret manager for sensitive values. If you must use a file, ensure it is not committed and has restricted permissions.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.