14. CLI & Libraries
Pick pragmatic libraries and structure CLIs for operability, testability, and cancellation.
Question: Which libraries are sensible picks at middle level and why?
Answer:
- CLI:
cobra
/pflag
; - HTTP router:
chi
; - logging: stdlib
slog
orzap
for performance; - metrics:
prometheus/client_golang
; - tracing:
otel
; - config: stdlib + optional
viper
/envconfig
; - migrations:
golang-migrate
; testing: stdlib +testify
.
Explanation: These are widely adopted, well‑maintained, and easy to justify in interviews.
Question: How do you structure a
cobra
CLI and handle cancellation?
Answer: Define a root command with persistent flags and subcommands. In RunE
, accept a Context
(cmd.Context()
) and respect cancellation.
Explanation: Wire signal handling (signal.NotifyContext
) at main
and pass the context to command execution and downstream operations.