Command-Line Tools and Configuration
What you will learn
By the end of this lesson, you will be able to:
- parse command-line flags with
flag.FlagSet; - read environment variables without hiding missing or invalid values;
- centralise configuration in a validated struct;
- return useful exit codes without making core logic call
os.Exit; - respond to process cancellation with
signal.NotifyContext.
Mental model: configuration is input
Configuration is untrusted input supplied at startup. Parse it once, validate it, and pass a typed value to the parts of the program that need it.
Avoid calling os.Getenv throughout business logic. That creates hidden dependencies and makes tests harder to control.
Parse flags with a dedicated FlagSet
type Config struct {
Address string
Verbose bool
}
func parseFlags(args []string) (Config, error) {
flags := flag.NewFlagSet("tasker", flag.ContinueOnError)
flags.SetOutput(io.Discard)
var config Config
flags.StringVar(&config.Address, "address", ":8080", "HTTP listen address")
flags.BoolVar(&config.Verbose, "verbose", false, "enable verbose logs")
if err := flags.Parse(args); err != nil {
return Config{}, err
}
if flags.NArg() != 0 {
return Config{}, fmt.Errorf("unexpected arguments: %v", flags.Args())
}
return config, nil
}
A private FlagSet is easier to test than package-level flags. ContinueOnError returns parsing failures instead of terminating the process.
Read environment variables explicitly
os.LookupEnv distinguishes a missing variable from a present empty value:
value, present := os.LookupEnv("TASKER_TIMEOUT")
if !present {
value = "5s"
}
timeout, err := time.ParseDuration(value)
if err != nil {
return Config{}, fmt.Errorf("TASKER_TIMEOUT: %w", err)
}
Decide precedence and document it. A common policy is:
- explicit flags;
- environment variables;
- configuration file;
- safe defaults.
The best order depends on the application, but it must be predictable.
Validate the complete configuration
func (c Config) Validate() error {
if c.Address == "" {
return errors.New("address must not be empty")
}
if c.Timeout <= 0 {
return errors.New("timeout must be greater than zero")
}
return nil
}
Validation belongs near parsing so the rest of the program can rely on a valid Config.
Never print secret values in validation errors or startup logs.
Keep main small
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "tasker:", err)
os.Exit(1)
}
}
func run(args []string) error {
config, err := parseFlags(args)
if err != nil {
return err
}
return start(config)
}
os.Exit skips deferred functions, so call it only at the outer process boundary. Inner functions should return errors.
React to shutdown signals
ctx, stop := signal.NotifyContext(
context.Background(),
os.Interrupt,
syscall.SIGTERM,
)
defer stop()
if err := runServer(ctx, config); err != nil {
return err
}
The context is cancelled when the process receives a configured signal. On platforms where a signal is unavailable or behaves differently, use the platform-appropriate set.
Common mistakes
- Reading configuration everywhere: dependencies become invisible and tests depend on the machine.
- Silently accepting invalid values: the application fails later and farther from the cause.
- Giving secrets defaults: missing credentials should normally stop startup rather than select a dangerous placeholder.
- Calling
log.Fataloros.Exitdeep inside packages: deferred cleanup is skipped and callers cannot recover or test failure behaviour. - Logging all environment variables: environments commonly contain secrets.
Practice
Create a Config with Address, Timeout, and LogLevel. Load defaults, allow environment overrides, then allow flag overrides. Validate every field and write table-driven tests for missing, valid, and malformed values.
Use one pure parsing function that receives args []string and an environment lookup function:
type LookupEnv func(string) (string, bool)
func LoadConfig(args []string, lookup LookupEnv) (Config, error) {
config := Config{Address: ":8080", Timeout: 5 * time.Second, LogLevel: "info"}
if value, ok := lookup("APP_TIMEOUT"); ok {
timeout, err := time.ParseDuration(value)
if err != nil {
return Config{}, fmt.Errorf("APP_TIMEOUT: %w", err)
}
config.Timeout = timeout
}
// Parse flags into config here, then call config.Validate().
return config, config.Validate()
}
Tests can pass a small map-backed lookup function rather than modifying the real process environment. The flag code follows the FlagSet example above. Keeping the environment and argument inputs explicit makes precedence testable.
Summary
- Parse configuration once at startup.
- Use typed fields and validate the complete result.
- Make precedence between flags, environment, files, and defaults explicit.
- Return errors from application logic and reserve
os.Exitformain. - Convert operating-system signals into cancellation at the process boundary.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.