Go CLI Design
A good CLI is a well-behaved Unix citizen: flags before magic, stdout
for data, stderr for diagnostics, exit codes that scripts can trust,
and Ctrl+C that actually stops it.
1. Structure: Testable main
func main() {
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
fs := flag.NewFlagSet("mytool", flag.ContinueOnError)
fs.SetOutput(stderr)
verbose := fs.Bool("v", false, "verbose output")
out := fs.String("o", "-", "output file (- for stdout)")
if err := fs.Parse(args); err != nil {
return err
}
// ...
_ = verbose
_ = out
return nil
}
signal.NotifyContext makes Ctrl+C cancel the context — every
long operation takes ctx and stops cleanly.
run receives args and streams — tests call it directly with
strings.Reader/bytes.Buffer, no subprocess needed.
os.Exit only in main (it skips defers).
2. stdout vs stderr
- stdout: the program's output — data, results, the thing you pipe.
- stderr: logs, progress, warnings, usage errors.
--json or detecting a pipe (!term.IsTerminal(int(os.Stdout.Fd())))
should silence decorations, never change the data.
// ✅ Good — result to stdout, progress to stderr
fmt.Fprintf(stderr, "processed %d files\n", n)
fmt.Fprintln(stdout, result)
// ❌ Bad — mixing both into stdout breaks every pipe
fmt.Printf("processing...\ndone: %s\n", result)
3. Exit Codes
| Code |
Meaning |
| 0 |
Success |
| 1 |
Generic runtime failure |
| 2 |
Usage error (bad flags/arguments) — flag package's convention |
| >2 |
Tool-specific, documented meanings (e.g. grep's 1 = no match) |
Map errors to codes in one place (main), not scattered os.Exit
calls. If scripts will branch on distinct failures, define sentinel
errors and translate: errors.Is(err, ErrNoMatch) → 1.
4. Flags and Arguments
- Flags for options, positional args for the primary operands:
mytool -v convert input.yaml, not mytool --input=input.yaml.
- Every flag has a usage string;
-h/-help output is your primary UX.
- Accept
- as "stdin/stdout" for file arguments.
- Defaults must be safe: destructive behavior behind explicit flags
(
--force), never default-on.
- Read secrets from env or files, never from flags (
ps leaks argv).
5. Subcommands
Standard library, fine up to a handful of commands:
switch fs.Arg(0) {
case "serve":
return runServe(ctx, fs.Args()[1:], stdout, stderr)
case "migrate":
return runMigrate(ctx, fs.Args()[1:], stdout, stderr)
default:
fmt.Fprintln(stderr, usage)
return fmt.Errorf("unknown command %q", fs.Arg(0))
}
Adopt Cobra when you need nested commands, generated help/completions,
and many flags — the structure pays for the dependency:
var rootCmd = &cobra.Command{Use: "mytool", SilenceUsage: true}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the server",
RunE: func(cmd *cobra.Command, args []string) error {
return serve(cmd.Context(), addr) // RunE returns errors; no os.Exit
},
}
func init() {
serveCmd.Flags().StringVar(&addr, "addr", ":8080", "listen address")
rootCmd.AddCommand(serveCmd)
}
Cobra rules: always RunE (never Run + os.Exit), set
SilenceUsage: true so runtime errors don't dump help, pass
cmd.Context() down. Add Viper only when layered config
(flags > env > file) is a real requirement — for most tools
flag + os.Getenv is enough.
6. Output for Humans and Machines
--json flag for machine consumption; table/text default for humans.
- Never emit ANSI colors when stdout is not a terminal or
NO_COLOR
is set.
- Progress bars/spinners go to stderr and only when it's a terminal.
Verification Checklist
run(ctx, args, stdin, stdout, stderr) pattern — logic testable without subprocess
signal.NotifyContext wired; long operations respect ctx cancellation
- Data on stdout, diagnostics on stderr — verified by piping
- Exit codes: 0 success, 2 usage, documented codes otherwise;
os.Exit only in main
- Every flag has usage text;
-h output reviewed
- accepted for stdin/stdout where files are taken
- Destructive actions require explicit flags
- No secrets via argv
- Cobra (if used): RunE everywhere, SilenceUsage, context propagated
- Colors/spinners disabled for non-TTY and NO_COLOR
1---
2name: go-cli
3description: >
4 Build command-line tools in Go: flag handling, subcommands, stdin/stdout
5 discipline, exit codes, signal handling, and when Cobra/Viper earn their
6 weight over the standard library. Use when: "build a CLI", "add a
7 subcommand", "parse flags", "exit codes", "handle Ctrl+C", "cobra
8 command", "read from stdin", "CLI UX".
9 Not for: HTTP APIs (go-api-design), scaffolding (go-project-layout),
10 service configuration (go-architecture-review).
11user-invocable: true
12license: MIT
13compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
14allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
15metadata:
16 source: https://skillmd.com/skills/eduardo-sl/go-cli
17 author: eduardo-sl
18 version: "1.1.1"
19---
20
21# Go CLI Design
22
23A good CLI is a well-behaved Unix citizen: flags before magic, stdout
24for data, stderr for diagnostics, exit codes that scripts can trust,
25and Ctrl+C that actually stops it.
26
27## 1. Structure: Testable main
28
29```go
30func main() {
31 ctx, stop := signal.NotifyContext(context.Background(),
32 os.Interrupt, syscall.SIGTERM)
33 defer stop()
34
35 if err := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr); err != nil {
36 fmt.Fprintln(os.Stderr, "error:", err)
37 os.Exit(1)
38 }
39}
40
41func run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
42 fs := flag.NewFlagSet("mytool", flag.ContinueOnError)
43 fs.SetOutput(stderr)
44 verbose := fs.Bool("v", false, "verbose output")
45 out := fs.String("o", "-", "output file (- for stdout)")
46 if err := fs.Parse(args); err != nil {
47 return err
48 }
49 // ...
50 _ = verbose
51 _ = out
52 return nil
53}
54```
55
56- `signal.NotifyContext` makes Ctrl+C cancel the context — every
57 long operation takes `ctx` and stops cleanly.
58- `run` receives args and streams — tests call it directly with
59 `strings.Reader`/`bytes.Buffer`, no subprocess needed.
60- `os.Exit` only in `main` (it skips defers).
61
62## 2. stdout vs stderr
63
64- **stdout**: the program's output — data, results, the thing you pipe.
65- **stderr**: logs, progress, warnings, usage errors.
66- `--json` or detecting a pipe (`!term.IsTerminal(int(os.Stdout.Fd()))`)
67 should silence decorations, never change the data.
68
69```go
70// ✅ Good — result to stdout, progress to stderr
71fmt.Fprintf(stderr, "processed %d files\n", n)
72fmt.Fprintln(stdout, result)
73
74// ❌ Bad — mixing both into stdout breaks every pipe
75fmt.Printf("processing...\ndone: %s\n", result)
76```
77
78## 3. Exit Codes
79
80| Code | Meaning |
81|---|---|
82| 0 | Success |
83| 1 | Generic runtime failure |
84| 2 | Usage error (bad flags/arguments) — flag package's convention |
85| >2 | Tool-specific, documented meanings (e.g. grep's 1 = no match) |
86
87Map errors to codes in one place (`main`), not scattered `os.Exit`
88calls. If scripts will branch on distinct failures, define sentinel
89errors and translate: `errors.Is(err, ErrNoMatch) → 1`.
90
91## 4. Flags and Arguments
92
93- Flags for options, positional args for the primary operands:
94 `mytool -v convert input.yaml`, not `mytool --input=input.yaml`.
95- Every flag has a usage string; `-h`/`-help` output is your primary UX.
96- Accept `-` as "stdin/stdout" for file arguments.
97- Defaults must be safe: destructive behavior behind explicit flags
98 (`--force`), never default-on.
99- Read secrets from env or files, never from flags (`ps` leaks argv).
100
101## 5. Subcommands
102
103Standard library, fine up to a handful of commands:
104
105```go
106switch fs.Arg(0) {
107case "serve":
108 return runServe(ctx, fs.Args()[1:], stdout, stderr)
109case "migrate":
110 return runMigrate(ctx, fs.Args()[1:], stdout, stderr)
111default:
112 fmt.Fprintln(stderr, usage)
113 return fmt.Errorf("unknown command %q", fs.Arg(0))
114}
115```
116
117Adopt **Cobra** when you need nested commands, generated help/completions,
118and many flags — the structure pays for the dependency:
119
120```go
121var rootCmd = &cobra.Command{Use: "mytool", SilenceUsage: true}
122
123var serveCmd = &cobra.Command{
124 Use: "serve",
125 Short: "Start the server",
126 RunE: func(cmd *cobra.Command, args []string) error {
127 return serve(cmd.Context(), addr) // RunE returns errors; no os.Exit
128 },
129}
130
131func init() {
132 serveCmd.Flags().StringVar(&addr, "addr", ":8080", "listen address")
133 rootCmd.AddCommand(serveCmd)
134}
135```
136
137Cobra rules: always `RunE` (never `Run` + `os.Exit`), set
138`SilenceUsage: true` so runtime errors don't dump help, pass
139`cmd.Context()` down. Add Viper only when layered config
140(flags > env > file) is a real requirement — for most tools
141`flag` + `os.Getenv` is enough.
142
143## 6. Output for Humans and Machines
144
145- `--json` flag for machine consumption; table/text default for humans.
146- Never emit ANSI colors when stdout is not a terminal or `NO_COLOR`
147 is set.
148- Progress bars/spinners go to stderr and only when it's a terminal.
149
150## Verification Checklist
151
1521. `run(ctx, args, stdin, stdout, stderr)` pattern — logic testable without subprocess
1532. `signal.NotifyContext` wired; long operations respect ctx cancellation
1543. Data on stdout, diagnostics on stderr — verified by piping
1554. Exit codes: 0 success, 2 usage, documented codes otherwise; `os.Exit` only in main
1565. Every flag has usage text; `-h` output reviewed
1576. `-` accepted for stdin/stdout where files are taken
1587. Destructive actions require explicit flags
1598. No secrets via argv
1609. Cobra (if used): RunE everywhere, SilenceUsage, context propagated
16110. Colors/spinners disabled for non-TTY and NO_COLOR