Stage 3 · Build
Building CLI Tools
Viper for Configuration
Env vars, config files, remote config, and pflag binding for layered configuration.
Why Viper
Viper is the standard configuration library for Go CLI tools. It handles config files, environment variables, command-line flags, and remote key-value stores — all with a unified API.
go get github.com/spf13/viper@latestViper works well with Cobra. Bind Cobra flags directly to Viper keys and get automatic precedence: flag > env > config file > default.
Configuration Sources
Viper reads configuration from multiple sources with a clear precedence order. This lets operators customize behavior without changing code or command-line flags.
Environment Variable Overrides
Environment variables override config file values. This is essential for container deployments where config files are impractical.
Prefer environment variables for deployment-specific values (ports, hosts, credentials). Use config files for structural configuration (feature flags, thresholds, lists). This follows the 12-factor app methodology.
Config to Struct Binding
Bind configuration to Go structs for type safety and IDE autocompletion. Viper uses mapstructure tags to map config keys to struct fields.
Live Reload
Viper can watch config files for changes. When the file is modified, Viper fires an event that your application can handle.
Sensible Defaults
Defaults make your tool work out of the box. Set reasonable defaults for every configuration option and document them in the help text.
Viper does not validate configuration values. Always validate after Unmarshal: check port ranges, required fields, and valid enum values. Return clear error messages for invalid configuration.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.