Write a Go command-line tool with flags and exit codes

11 steps · about 3 h 10 min · Beginner

  1. Go by Example: Command-Line Flags (tutorial, Go by Example, 10 min)

    A short, runnable first look at declaring flags, calling flag.Parse() and reading positional arguments.

  2. flag package - flag - Go Packages (reference, Go standard library docs, 20 min)

    The official reference for flag syntax, flag.Var, custom types and the rule that parsing stops at the first non-flag argument.

  3. Go flag Package: Parsing Command-Line Arguments (article, ZetCode, 20 min)

    Adds worked examples of typed flags, flag.Args(), duration flags and a first look at subcommands with NewFlagSet.

  4. Exit an app in Go (article, GoSamples, 10 min)

    Introduces os.Exit, what a status code means and why deferred functions are skipped.

  5. Runnable Go Docs: Command-Line Arguments (doc, Coddy, 15 min)

    Covers the exit-code conventions (0, 1, 2) and the run() pattern that keeps os.Exit in one place in main.

  6. Building a Simple CLI Tool with Golang (article, Rapid7, 25 min)

    Walks through building a complete tool with custom flag types and subcommands using flag.FlagSet.

  7. Control the exit code - errorhandling (guide, errorhandling docs, 15 min)

    Explains why a single exit path matters and how to map different errors to different codes.

  8. Add a test - The Go Programming Language (tutorial, go.dev, 20 min)

    Teaches go test basics, which you need before you can test your tool's run() function.

  9. Flipping the script: a smarter way to test Go binaries (blog, Bitfield Consulting (John Arundel), 20 min)

    Shows how testscript runs your CLI like a user would and asserts on its output.

  10. testscript: a DSL for testing CLI tools in Go (blog, Bitfield Consulting (John Arundel), 25 min)

    Applies testscript to your own tool, covering missing arguments, failures and golden files.

  11. pflag package - github.com/spf13/pflag - Go Packages (reference, spf13/pflag, 10 min)

    A last step: the drop-in replacement that adds POSIX/GNU-style --long and -s flags once the standard library feels limiting.