PluginBench
Skill
Pass
Audit score 90

golang-cli

samber/cc-skills-golang

Build production Go CLI tools with Cobra and Viper—command structure, flags, config layering, and exit codes.

What is golang-cli?

Golang CLI application development skill for building, extending, or reviewing Go command-line tools. Use when working with CLI command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, and argument validation. Covers Cobra, Viper, and urfave/cli frameworks.

  • Scaffold and organize CLI projects with standard cmd/ structure and minimal main.go
  • Define commands, subcommands, and flags with Cobra; bind flags to Viper for config layering (flags → env vars → config file → defaults)
  • Validate positional arguments using built-in Cobra validators (NoArgs, ExactArgs, RangeArgs, etc.)
  • Embed version info at compile time via ldflags and implement version commands
  • Handle exit codes following Unix conventions (0=success, 1=general error, 2=usage error, 64-78=sysexits)
  • Manage I/O discipline: stdout for output, stderr for logs/errors; detect terminal vs pipe; support machine-readable formats (JSON, table, plain)

How to install golang-cli

npx skills add https://github.com/samber/cc-skills-golang --skill golang-cli
Prerequisites
  • Go installed and in PATH
  • Familiarity with Go packages and module management (go.mod)
Claude Code
Cursor
Windsurf
Cline

How to use golang-cli

  1. 1.Read the project structure section and organize your CLI code under cmd/myapp/ with one file per command
  2. 2.Set up the root command in root.go with SilenceUsage and SilenceErrors enabled, and initialize Viper in PersistentPreRunE
  3. 3.Define flags (persistent and local) in each command file and bind them to Viper using viper.BindPFlag()
  4. 4.Add subcommands by creating separate files and registering them in init() functions
  5. 5.Implement argument validation using Cobra validators (NoArgs, ExactArgs, RangeArgs, etc.)
  6. 6.Configure Viper to read from config files, environment variables, and flags in the correct precedence order
  7. 7.Embed version info at build time using go build -ldflags and implement a version command
  8. 8.Ensure stdout is used only for program output and stderr for logs/errors; support --output flag for machine-readable formats

Use cases

Good for
  • Building a new CLI tool from scratch with subcommands, persistent flags, and config file support
  • Adding new subcommands or flags to an existing Cobra-based CLI while maintaining consistency
  • Auditing a CLI for correctness: verifying SilenceUsage/SilenceErrors, flag-to-Viper binding, exit codes, and stdout/stderr discipline
  • Embedding build metadata (version, commit hash) into a CLI binary for distribution
  • Implementing configuration layering so users can set values via flags, environment variables, or config files with proper precedence
Who it's for
  • Go developers building command-line tools and utilities
  • DevOps engineers creating deployment or infrastructure CLIs
  • Backend developers extending existing Cobra-based CLIs (kubectl, docker, gh, hugo)
  • Teams distributing Go binaries via goreleaser or similar tools

golang-cli FAQ

When should I use Cobra vs stdlib flag package?

Use Cobra + Viper for any CLI with subcommands, multiple flags, or configuration layering. Use stdlib flag only for trivial single-purpose tools with no subcommands and few flags.

How do I make a flag required?

Use cmd.MarkFlagRequired("flagname") in the command's init() function. For mutual exclusivity or one-of constraints, use MarkFlagsMutuallyExclusive() or MarkFlagsOneRequired().

What is the correct precedence for configuration values?

CLI flags (highest) → environment variables → config file → defaults (lowest). Bind flags to Viper with viper.BindPFlag() to ensure flags override env vars and config file values.

How do I embed version information in my binary?

Use go build -ldflags "-X main.Version=1.0.0" to inject version at compile time. Store it in a package-level variable and expose it via a version command.

Should diagnostic output go to stdout or stderr?

Always write logs, errors, and diagnostics to stderr. Reserve stdout only for program output that users might pipe to other tools.

Full instructions (SKILL.md)

Source of truth, from samber/cc-skills-golang.


name: golang-cli description: "Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, argument validation, and CLI unit testing. Also triggers when code uses cobra, viper, or urfave/cli. For cobra-specific APIs → See samber/cc-skills-golang@golang-spf13-cobra skill; for viper configuration layering → See samber/cc-skills-golang@golang-spf13-viper skill." user-invocable: true license: MIT compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang. metadata: author: samber version: "1.2.0" openclaw: emoji: "💻" homepage: https://github.com/samber/cc-skills-golang requires: bins: - go install: [] allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:*) Agent AskUserQuestion

Persona: You are a Go CLI engineer. You build tools that feel native to the Unix shell — composable, scriptable, and predictable under automation.

Modes:

  • Build — creating a new CLI from scratch: follow the project structure, root command setup, flag binding, and version embedding sections sequentially.
  • Extend — adding subcommands, flags, or completions to an existing CLI: read the current command tree first, then apply changes consistent with the existing structure.
  • Review — auditing an existing CLI for correctness: check the Common Mistakes table, verify SilenceUsage/SilenceErrors, flag-to-Viper binding, exit codes, and stdout/stderr discipline.

Go CLI Best Practices

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.

Quick Reference

ConcernPackage / Tool
Commands & flagsgithub.com/spf13/cobra
Configurationgithub.com/spf13/viper
Flag parsinggithub.com/spf13/pflag (via Cobra)
Colored outputgithub.com/fatih/color
Table outputgithub.com/olekukonko/tablewriter
Interactive promptsgithub.com/charmbracelet/bubbletea
Version injectiongo build -ldflags
Distributiongoreleaser

Project Structure

Organize CLI commands in cmd/myapp/ with one file per command. Keep main.go minimal — it only calls Execute().

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.

Root Command Setup

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 error
  • SilenceErrors: true MUST be set — lets you control error output format yourself
  • PersistentPreRunE runs before every subcommand, so config is always initialized
  • Logs go to stderr, output goes to stdout

Subcommands

Add 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.

Flags

See assets/examples/flags.go for all flag patterns:

Persistent vs Local

  • Persistent flags are inherited by all subcommands (e.g., --config)
  • Local flags only apply to the command they're defined on (e.g., --port)

Required Flags

Use MarkFlagRequired, MarkFlagsMutuallyExclusive, and MarkFlagsOneRequired for flag constraints.

Flag Validation with RegisterFlagCompletionFunc

Provide completion suggestions for flag values.

Always Bind Flags to Viper

This ensures viper.GetInt("port") returns the flag value, env var MYAPP_PORT, or config file value — whichever has highest precedence.

Argument Validation

Cobra provides built-in validators for positional arguments. See assets/examples/args.go for both built-in and custom validation examples.

ValidatorDescription
cobra.NoArgsFails if any args provided
cobra.ExactArgs(n)Requires exactly n args
cobra.MinimumNArgs(n)Requires at least n args
cobra.MaximumNArgs(n)Allows at most n args
cobra.RangeArgs(min, max)Requires between min and max
cobra.ExactValidArgs(n)Exactly n args, must be in ValidArgs

Configuration with Viper

Viper resolves configuration values in this order (highest to lowest precedence):

  1. CLI flags (explicit user input)
  2. Environment variables (deployment config)
  3. Config file (persistent settings)
  4. Defaults (set in code)

See assets/examples/config.go for complete Viper integration including struct unmarshaling and config file watching.

Example Config File (.myapp.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:

  • Flag: --port 9090
  • Env var: MYAPP_PORT=9090
  • Config file: port: 9090

Version and Build Info

Version SHOULD be embedded at compile time using ldflags. See assets/examples/version.go for the version command and build instructions.

Exit Codes

Exit codes MUST follow Unix conventions:

CodeMeaningWhen to Use
0SuccessOperation completed normally
1General errorRuntime failure
2Usage errorInvalid flags or arguments
64-78BSD sysexitsSpecific error categories
126Cannot executePermission denied
127Command not foundMissing dependency
128+NSignal NTerminated by signal (e.g., 130 = SIGINT)

See assets/examples/exit_codes.go for a pattern mapping errors to exit codes.

I/O Patterns

See assets/examples/output.go for all I/O patterns:

  • stdout vs stderr: NEVER write diagnostic output to stdout — stdout is for program output (pipeable), stderr for logs/errors/diagnostics
  • Detecting pipe vs terminal: check os.ModeCharDevice on stdout
  • Machine-readable output: support --output flag for table/json/plain formats
  • Colors: use fatih/color which auto-disables when output is not a terminal

Signal Handling

Signal handling MUST use signal.NotifyContext to propagate cancellation through context. See assets/examples/signal.go for graceful HTTP server shutdown.

Shell Completions

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.

Testing CLI Commands

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.

Common Mistakes

MistakeFix
Writing to os.Stdout directlyTests can't capture output. Use cmd.OutOrStdout() which tests can redirect to a buffer
Calling os.Exit() inside RunECobra's error handling, deferred functions, and cleanup code never run. Return an error, let main() decide
Not binding flags to ViperFlags won't be configurable via env/config. Call viper.BindPFlag for every configurable flag
Missing viper.SetEnvPrefixPORT collides with other tools. Use a prefix (MYAPP_PORT) to namespace env vars
Logging to stdoutUnix pipes chain stdout — logs corrupt the data stream for the next program. Logs go to stderr
Printing usage on every errorFull help text on every error is noise. Set SilenceUsage: true, save full usage for --help
Config file requiredUsers without a config file get a crash. Ignore viper.ConfigFileNotFoundError — config should be optional
Not using PersistentPreRunEConfig initialization must happen before any subcommand. Use root's PersistentPreRunE
Hardcoded version stringVersion gets out of sync with tags. Inject via ldflags at build time from git tags
Not supporting --output formatScripts can't parse human-readable output. Add JSON/table/plain for machine consumption

Related Skills

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.