golang-cli

作者: samber

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

npx skills add https://github.com/samber/cc-skills-golang --skill golang-cli

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.

來自 samber 的更多技能

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
符合慣例的 Golang 設計模式 — 函數選項、建構子、錯誤流程與串聯、資源管理與生命週期、優雅關閉、韌性、架構、依賴注入、資料處理、串流等。適用於明確選擇架構模式、實作函數選項、設計建構子 API、設定優雅關閉、應用韌性模式,或詢問哪種慣用 Go 模式適合特定問題時。
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Golang 性能優化模式與方法論 - 若遇到 X 瓶頸,則應用 Y。涵蓋減少分配、CPU 效率、記憶體佈局、GC 調校、池化、快取以及熱路徑優化。適用於當性能分析或基準測試已識別出瓶頸,且需要正確的優化模式來解決時。亦適用於進行性能代碼審查時,提出改進建議或可協助快速識別性能增益的基準測試。不適用於測量方法論(→...
developmentcode-review
golang-security
samber
Golang的安全最佳實踐與漏洞防範。涵蓋注入攻擊(SQL、命令、XSS)、密碼學、檔案系統安全、網路安全、Cookie、機密管理、記憶體安全及日誌記錄。適用於撰寫、審查或稽核Go程式碼的安全性,或處理涉及加密、I/O、機密管理、使用者輸入處理或身分驗證的高風險程式碼。包含安全工具的配置。
securitycode-reviewdevelopment
golang-database
samber
Go 資料庫存取的全面指南 — 參數化查詢、結構掃描、可空欄位、交易、隔離層級、SELECT FOR UPDATE、連線池、批次處理、上下文傳遞與遷移工具。適用於撰寫、審查或除錯與 PostgreSQL、MariaDB、MySQL 或 SQLite 互動的 Golang 程式碼;資料庫測試;或關於 database/sql、sqlx 或 pgx 的問題。不產生資料庫結構或遷移 SQL。
developmentdatabase
golang-lint
samber
針對 Golang 專案的 lint 最佳實務與 golangci-lint 配置 — 執行 linter、設定 .golangci.yml、使用 nolint 指令抑制警告、解讀 lint 輸出,以及選擇 linter。適用於配置 golangci-lint、詢問 lint 警告或 nolint 抑制方式、設定程式碼品質工具,或挑選 linter 時。亦適用於使用者提及 golangci-lint、go vet、staticcheck 或 revive 時。
developmentcode-reviewtesting