Build command-line tools in Go: flag handling, subcommands, stdin/stdout discipline, exit codes, signal handling, and when Cobra/Viper earn their weight over the standard library.
Ships in go-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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.
Detailed reference material, loaded on demand:
references/testing-and-versioning.md — exit-code mapping in main,
golden-file and testscript tests, version from build info, completions.Read a reference file only when the summary below is not enough.
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. Call stop() once the
context is done so a second Ctrl+C kills a stuck program immediately.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).--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)
| 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. With flag.ContinueOnError, -h returns flag.ErrHelp — exit 0
for it, and wrap parse errors in a usage error type so main can exit 2.
Exit 130 after Ctrl+C. If scripts will branch on distinct failures, define
sentinel errors and translate: errors.Is(err, ErrNoMatch) → 1.
mytool -v convert input.yaml, not mytool --input=input.yaml.-h/-help output is your primary UX.- as "stdin/stdout" for file arguments.--force), never default-on.ps leaks argv).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.
--json flag for machine consumption; table/text default for humans.NO_COLOR
is set.Test run directly with buffers, comparing stdout against golden files
regenerated with -update. For end-to-end behavior — real binary, exit
codes, stdin — use testscript (.txtar scripts), the format the Go
command tests itself with.
mytool version reads debug.ReadBuildInfo(): since Go 1.24 the main
module's version comes from the VCS tag, and vcs.revision from the
build settings. Fall back to -ldflags "-X main.version=..." only when
building without VCS metadata.
Cobra generates completion bash|zsh|fish|powershell; add
ValidArgsFunction for dynamic values. Without Cobra, ship a static
completion script with the release.
Examples for sections 3 and 7-9: references/testing-and-versioning.md.
run(ctx, args, stdin, stdout, stderr) pattern — logic testable without subprocesssignal.NotifyContext wired; long operations respect ctx cancellationos.Exit only in main-h output reviewed- accepted for stdin/stdout where files are taken-h exits 0, usage errors exit 2, Ctrl+C exits 130version output comes from build info; golden or testscript tests cover the CLI surfaceWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
35 skills in this plugin
/git-commitStructured git commit messages following Conventional Commits format for Go projects. Generates well-scoped, atomic commits with clear descriptions. Use when committing changes, writing commit messages, preparing PRs, or reviewing commit history quality. Trigger examples: "commit these changes", "create commit", "commit message", "prepare PR", "squash commits". Not for: code review (go-code-review), changelog generation.
/go-api-designHTTP/REST API design for Go services: handlers, ServeMux routing, middleware, request validation, pagination, idempotency, health checks, error responses, and graceful shutdown. Use when designing APIs, writing HTTP handlers, implementing middleware, or structuring REST endpoints. Trigger examples: "design API", "REST endpoints", "HTTP handler", "middleware pattern", "graceful shutdown", "API versioning". Not for: gRPC services (go-grpc), spec-first OpenAPI work (go-openapi), general architecture (go-architecture-review), concurrency in handlers (go-concurrency-review).
/go-architecture-reviewReview Go project architecture: package structure, dependency direction, layering, separation of concerns, domain modeling, and module boundaries. Use when reviewing architecture, designing package layout, evaluating dependency graphs, or refactoring monoliths into modules. Trigger examples: "review architecture", "package structure", "project layout", "dependency direction", "clean architecture Go", "module boundaries". Not for: code-level style (go-coding-standards), endpoint design (go-api-design).
/go-agent-skills:go-clifrom go-agent-skills
npx claudepluginhub eduardo-sl/go-agent-skills --plugin go-agent-skillsOther plugins' skills for the same job