Module lessons (4/5)
Mini-project: a CLI with flag
flag package, commands and sub-commands, exit code, log vs fmt for outputs.
What you'll learn in this lesson
- Define and parse command line options and positional arguments using the
flagpackage. - Separate pipe-able output (
os.Stdout) from diagnostics/errors (os.Stderr) with exit code0,1,2. - Isolate the CLI logic in a
run(args, stdout, stderr)function usingflag.NewFlagSet. - Adopt
log/slog(Go 1.21+) for structured logging and remember the impact ofos.Exitondefer.
Overview
A well-designed Go CLI compiles to a single static binary, respects the UNIX convention of Stdout vs Stderr, returns meaningful exit codes, and isolates the flag configuration so that it remains testable in memory without touching the global process.
The functions flag.Int, flag.String and flag.Bool return pointers populated only after flag.Parse(), while the remaining parameters are accessible with flag.Args():
Sections covered in this lesson
- 1The
flagpackage and positional arguments - 2Separate
Stdout,Stderrand exit code - 3Pattern testable with
flag.NewFlagSet - 4Modern Structured Logging (
log/slog) - 5Multiple subcommands with
switch - 6Guided practice
Unlock "Mini-project: a CLI with flag" and the full Course Go curriculum
`flag` package, commands and sub-commands, exit code, `log` vs `fmt` for outputs.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.