Skip to content
cccskills
FreePublished on GitHub

golang-cli

Build, extend, or review Go command-line tools with clear commands, flags, and configuration priorities. It guides output formats, exit codes, shell completion, cancellation, and tests so tools behave predictably in scripts and terminals.

OriginalShow the original 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.

See how to install

Good for

  • Build a Go command-line tool with subcommands
  • Combine flags, environment variables, and configuration files
  • Review output and exit codes for use in scripts
  • Add shell completion and command tests

Files included (14)

  • SKILL.md10.0 KB
  • assets/examples/args.go1020 B
  • assets/examples/cli_test.go1.2 KB
  • assets/examples/completion.go1.6 KB
  • assets/examples/config.go1.7 KB
  • assets/examples/exit_codes.go494 B
  • assets/examples/flags.go1.3 KB
  • assets/examples/main.go120 B
  • assets/examples/output.go1.7 KB
  • assets/examples/root.go1.8 KB
  • assets/examples/serve.go735 B
  • assets/examples/signal.go831 B
  • assets/examples/version.go871 B
  • evals/evals.json16.0 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

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.

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

golang-benchmark

FreeSummary

Measure Go performance by writing benchmarks, examining CPU and memory profiles, and comparing repeated runs with benchstat. Use the results to assess code changes, detect slowdowns in CI, and investigate production performance.

  • Compare performance before and after a code change
  • Investigate CPU usage and memory allocations
  • Detect performance regressions in CI
samber/cc-skills-golang3.6KUpdated Oct 1, 2026

Make Go code easier to read by reviewing line breaks, variable declarations, branching, function parameters, and file organization. Provides concrete style guidance for implementation, code reviews, and project standards where formatting tools alone cannot judge clarity.

  • Reviewing Go code for readability
  • Simplifying nested branches and complex conditions
  • Improving long function signatures and calls
samber/cc-skills-golang3.6KUpdated Oct 1, 2026

Design and review concurrent Go code with clear goroutine ownership, shutdown paths, and error handling. Choose channels, locks, or atomic operations to protect shared data, and structure worker pools with controlled concurrency and cancellation.

  • Design goroutine shutdown and cancellation
  • Choose channels or mutexes for concurrent code
  • Protect shared maps and counters
samber/cc-skills-golang3.6KUpdated Oct 1, 2026

golang-context

FreeSummary

Design how Go requests carry cancellation signals, time limits, and request metadata through application layers. Helps investigate work that continues after cancellation, choose suitable context types, and separate background tasks from the request lifecycle.

  • Reviewing context propagation from HTTP handlers to database calls
  • Investigating missing cancellation and lingering timers
  • Keeping background work running after a request ends
samber/cc-skills-golang3.6KUpdated Oct 1, 2026

Set up or improve GitHub Actions pipelines for Go projects. Configure automated tests, code checks, vulnerability scans, dependency update bots, releases, and Docker publishing, with workflow templates and repository settings that control permissions and merge requirements.

  • Set up automated tests and code checks for Go
  • Add vulnerability scanning to a pipeline
  • Configure dependency update bots
samber/cc-skills-golang3.6KUpdated Oct 1, 2026

Choose and use Go data structures based on access patterns, memory use, and copying behavior. It covers slices, maps, arrays, standard containers, string building, generic collections, and pointer types, with guidance on allocation and shared data.

  • Choose between slices, maps, arrays, and standard containers
  • Plan capacity allocation for slices and maps
  • Review which data remains shared after copying
samber/cc-skills-golang3.6KUpdated Oct 1, 2026

See all skills by samber

Report a problem with this skill