Building CLIs With flag, os.Getenv, and Exit Codes
Parse command-line flags, fall back to environment variables, write errors to stderr, and return testable exit codes. After this, your Go CLIs behave cleanly in scripts and containers.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
Command-line tools and containerized services share the same operational contract: they accept settings from flags and environment variables, send real data to os.Stdout, send errors to os.Stderr, and communicate success or failure back to bash, Docker, or CI with an integer exit code.
Skip ahead
If you already keep main() down to os.Exit(run(os.Args[1:])), parse flags with flag.NewFlagSet, default to os.Getenv, and write errors to os.Stderr, take the section quiz to wrap up Go for Beginners.
Experiment 1: Why calling os.Exit(1) inside helpers breaks cleanup and tests
When a helper function hits a bad flag or missing file, calling os.Exit(1) (or log.Fatal, which calls os.Exit(1)) terminates the OS process immediately—skipping every deferred cleanup and killing the entire go test runner if you try to test it! Instead, return an integer exit code from a run() function so every defer executes cleanly before main() exits:
package main
import "fmt"
func run() int {
defer fmt.Println("cleanup ran!")
return 1
}
func main() {
code := run()
fmt.Println("would exit with:", code)
}
cleanup ran!
would exit with: 1
In a real binary, main() is simply os.Exit(run(os.Args[1:])). All flag parsing, file closing, and cleanup defers finish inside run before os.Exit terminates the process.
Experiment 2: Flags overriding environment variables with flag.NewFlagSet
In Docker and Kubernetes, configuration usually arrives via environment variables (PORT=9090), while local developers often override it with a CLI flag (-port 8080). Using flag.NewFlagSet with os.Getenv("PORT") as the default supports both—and avoids mutating the global flag.CommandLine state so unit tests can invoke run(...) repeatedly:
package main
import (
"flag"
"fmt"
"os"
)
func run(args []string) int {
fs := flag.NewFlagSet("portcheck", flag.ContinueOnError)
port := fs.String("port", os.Getenv("PORT"), "listen port")
if err := fs.Parse(args); err != nil {
return 2
}
if *port == "" {
fmt.Fprintln(os.Stderr, "error: -port or PORT is required")
return 1
}
fmt.Printf("listening on :%s\n", *port)
return 0
}
func main() {
fmt.Println("missing:", run(nil))
os.Setenv("PORT", "9090")
fmt.Println("from_env:", run(nil))
fmt.Println("from_flag:", run([]string{"-port", "8080"}))
}
error: -port or PORT is required
missing: 1
listening on :9090
from_env: 0
listening on :8080
from_flag: 0
Experiment 3: Why os.Stderr keeps shell pipes working
Suppose someone pipes your CLI's JSON output into jq: ./portcheck | jq .. If your tool prints "error: -port is required" using fmt.Println(...) (which writes to os.Stdout), jq tries to parse that error sentence as JSON and fails cryptically! Writing errors with fmt.Fprintln(os.Stderr, ...) sends diagnostics to the terminal while keeping os.Stdout strictly for structured output.
Experiment 4: Exit codes that scripts and containers expect
0: Command succeeded cleanly.1: Runtime, config, or validation error (e.g., missing requiredPORT, failed HTTP check).2: Invalid CLI flag syntax or usage error (unknown flag, non-integer value for anintflag).
Common mistakes
- Calling
log.Fatalinside library or helper functions: Bypasses alldeferstatements and makes unit testing impossible. Return an error (or exit code fromrun) instead. - Putting flags after positional arguments: Go's standard
flagpackage stops scanning flags at the first non-flag argument, somycli input.csv -port 8080ignores-port. Always place flags first. - Using global
flag.String+flag.Parse()inside testable functions: Calling it twice in tests panics withflag redefined; always useflag.NewFlagSet.
💡 Tip
Pass stdout, stderr io.Writer into run(args []string, stdout, stderr io.Writer) int when you want unit tests to assert exact terminal output using bytes.Buffer—no OS process spawning needed.
What happens if you skip this step
CLIs that exit inside helpers or print errors to stdout skip file cleanups, break automated shell scripts and Docker healthchecks, and force slow end-to-end subprocess tests for simple flag checks.
You call defer tempFile.Close() at the top of a helper function, then call os.Exit(1) ten lines later on an error. Does tempFile.Close() run before the process exits?
About
Parse command-line flags, fall back to environment variables, write errors to stderr, and return testable exit codes. After this, your Go CLIs behave cleanly in scripts and containers.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.