Home › Go › Go CLI (Cobra) CLAUDE.md
Go CLI (Cobra) CLAUDE.md
CLAUDE.md for command-line tools in Go 1.27 with Cobra: commands, flags, output formats, exit codes, and tests.
Claude Code (CLAUDE.md)Go
How to use
Save this as CLAUDE.md in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.
Note: Review and test before use. Provided as is, without warranty. See Terms.
CLAUDE.mdDownload # CLAUDE.md: Go CLI with Cobra
## Commands
`go build -o bin/tool ./cmd/tool` · `go test ./...` · `golangci-lint run` · try it: `go run ./cmd/tool --help`
## Structure
- `cmd/tool/main.go` calls `cli.Execute()` and maps the error to an exit code.
- `internal/cli/` holds one file per command (`root.go`, `list.go`, ...), each with a constructor `newListCmd(deps) *cobra.Command`; no package-level command globals or `init()` wiring.
- Real work lives in `internal/<domain>/`, callable without Cobra.
## Command rules
- Use `RunE` and return errors; never `os.Exit` or `log.Fatal` inside commands.
- Flags declared on the command that uses them; persistent flags only for truly global options (`--config`, `--verbose`). Validate with `Args: cobra.ExactArgs(1)` and `MarkFlagRequired`.
- Output: human-readable by default to `cmd.OutOrStdout()`; `--output json` for scripts with stable field names. Diagnostics and progress go to `cmd.ErrOrStderr()`.
- Exit codes: 0 success, 1 runtime error, 2 usage error.
- Respect `NO_COLOR` and non-TTY output (no spinners/colors when piped).
- Destructive commands ask for confirmation unless `--yes` is passed.
- Support `context` cancellation on Ctrl-C via `signal.NotifyContext` passed to `ExecuteContext`.
- Provide shell completion via Cobra's `completion` command.
## Tests
Build the root command in tests, call `SetArgs`, `SetOut`, `SetErr`, and assert on output and errors (golden files for long output).