Persona: You are a Go CLI engineer. You build tools that feel native to the Unix shell — composable, scriptable, and predictable under automation.
Modes:
SilenceUsage/ SilenceErrors, flag-to-Viper binding, exit codes, and stdout/stderr discipline.Use Cobra + Viper as the default stack for Go CLI applications. Cobra provides the command/subcommand/flag structure and Viper handles configuration from files, environment variables, and flags with automatic layering. This combination powers kubectl, docker, gh, hugo, and most production Go CLIs.
When using Cobra or Viper, refer to the library's official documentation and code examples for current API signatures.
For trivial single-purpose tools with no subcommands and few flags, stdlib flag is sufficient.
ConcernPackage / ToolCommands & flagsgithub.com/spf13/cobraConfigurationgithub.com/spf13/viperFlag parsinggithub.com/spf13/pflag (via Cobra)Colored outputgithub.com/fatih/colorTable outputgithub.com/olekukonko/tablewriterInteractive promptsgithub.com/charmbracelet/bubbleteaVersion injectiongo build -ldflagsDistributiongoreleaser
Organize CLI commands in cmd/myapp/ with one file per command. Keep main.go minimal — it only calls Execute().
text
myapp/
├── cmd/
│ └── myapp/
│ ├── main.go # package main, only calls Execute()
│ ├── root.go # Root command + Viper init
│ ├── serve.go # "serve" subcommand
│ ├── migrate.go # "migrate" subcommand
│ └── version.go # "version" subcommand
├── go.mod
└── go.sum
main.go should be minimal — see assets/examples/main.go.
The root command initializes Viper configuration and sets up global behavior via PersistentPreRunE. See assets/examples/root.go.
Key points:
SilenceUsage: true MUST be set — prevents printing the full usage text on every errorSilenceErrors: true MUST be set — lets you control error output format yourselfPersistentPreRunE runs before every subcommand, so config is always initializedAdd subcommands by creating separate files in cmd/myapp/ and registering them in init(). See assets/examples/serve.go for a complete subcommand example including command groups.
See assets/examples/flags.go for all flag patterns:
--config)--port)Use MarkFlagRequired, MarkFlagsMutuallyExclusive, and MarkFlagsOneRequired for flag constraints.
Provide completion suggestions for flag values.
This ensures viper.GetInt("port") returns the flag value, env var MYAPP_PORT, or config file value — whichever has highest precedence.
Cobra provides built-in validators for positional arguments. See assets/examples/args.go for both built-in and custom validation examples.
ValidatorDescriptioncobra.NoArgsFails if any args providedcobra.ExactArgs(n)Requires exactly n argscobra.MinimumNArgs(n)Requires at least n argscobra.MaximumNArgs(n)Allows at most n argscobra.RangeArgs(min, max)Requires between min and maxcobra.ExactValidArgs(n)Exactly n args, must be in ValidArgs
Viper resolves configuration values in this order (highest to lowest precedence):
See assets/examples/config.go for complete Viper integration including struct unmarshaling and config file watching.
yaml
port: 8080
host: localhost
log-level: info
database:
dsn: postgres://localhost:5432/myapp
max-conn: 25
With the setup above, these are all equivalent:
--port 9090MYAPP_PORT=9090port: 9090Version SHOULD be embedded at compile time using ldflags. See assets/examples/version.go for the version command and build instructions.
Exit codes MUST follow Unix conventions:
CodeMeaningWhen to Use0SuccessOperation completed normally1General errorRuntime failure2Usage errorInvalid flags or arguments64-78BSD sysexitsSpecific error categories126Cannot executePermission denied127Command not foundMissing dependency128+NSignal NTerminated by signal (e.g., 130 = SIGINT)
See assets/examples/exit_codes.go for a pattern mapping errors to exit codes.
See assets/examples/output.go for all I/O patterns:
os.ModeCharDevice on stdout--output flag for table/json/plain formatsfatih/color which auto-disables when output is not a terminalSignal handling MUST use signal.NotifyContext to propagate cancellation through context. See assets/examples/signal.go for graceful HTTP server shutdown.
Cobra generates completions for bash, zsh, fish, and PowerShell automatically. See assets/examples/completion.go for both the completion command and custom flag/argument completions.
Test commands by executing them programmatically and capturing output. See assets/examples/cli_test.go.
Use cmd.OutOrStdout() and cmd.ErrOrStderr() in commands (instead of os.Stdout / os.Stderr) so output can be captured in tests.
MistakeFixWriting to os.Stdout directlyTests can't capture output. Use cmd.OutOrStdout() which tests can redirect to a bufferCalling os.Exit() inside RunECobra's error handling, deferred functions, and cleanup code never run. Return an error, let main() decideNot binding flags to ViperFlags won't be configurable via env/config. Call viper.BindPFlag for every configurable flagMissing viper.SetEnvPrefix``PORT collides with other tools. Use a prefix ( MYAPP_PORT) to namespace env varsLogging to stdoutUnix pipes chain stdout — logs corrupt the data stream for the next program. Logs go to stderrPrinting usage on every errorFull help text on every error is noise. Set SilenceUsage: true, save full usage for --helpConfig file requiredUsers without a config file get a crash. Ignore viper.ConfigFileNotFoundError — config should be optionalNot using PersistentPreRunEConfig initialization must happen before any subcommand. Use root's PersistentPreRunEHardcoded version stringVersion gets out of sync with tags. Inject via ldflags at build time from git tagsNot supporting --output formatScripts can't parse human-readable output. Add JSON/table/plain for machine consumption
See samber/cc-skills-golang@golang-project-layout, samber/cc-skills-golang@golang-dependency-injection, samber/cc-skills-golang@golang-testing, samber/cc-skills-golang@golang-design-patterns skills.