Skip to main content
Module 10 · Lesson 4 of 549/50 in the course~18 min
Module lessons (4/5)

Mini-project: a CLI with flag

Lesson preview5 hands-on exercises readyCourse Go · Module 10 — Idiomatic practice

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 flag package.
  • Separate pipe-able output (os.Stdout) from diagnostics/errors (os.Stderr) with exit code 0, 1, 2.
  • Isolate the CLI logic in a run(args, stdout, stderr) function using flag.NewFlagSet.
  • Adopt log/slog (Go 1.21+) for structured logging and remember the impact of os.Exit on defer.

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

  1. 1The flag package and positional arguments
  2. 2Separate Stdout, Stderr and exit code
  3. 3Pattern testable with flag.NewFlagSet
  4. 4Modern Structured Logging (log/slog)
  5. 5Multiple subcommands with switch
  6. 6Guided practice
Pro Lesson · Module 10 — Idiomatic 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.