Golang Configuration
Priority: P1 (STANDARD)
Principles
- 12-Factor App: Store config in environment variables.
- Typed Config: Load config into a struct, validate immediately.
- Secrets: Never commit secrets. Use env vars or secret managers.
- No Globals: Return a Config struct and inject it.
Implementation Workflow
- Define Config struct — Create a typed struct with all required fields.
- Load defaults — Set sensible defaults for non-secret values.
- Override from file — Optionally load from YAML/JSON config file.
- Override from env — Environment variables take highest priority.
- Validate at startup — Crash immediately on missing required config.
- Inject via constructor — Pass Config to services; never use global config vars.
See config struct and usage examples
Libraries
- Standard Lib:
os.Getenvfor simple apps. - Viper: Industry standard for complex configs (env, files, remote).
- Koanf: Lighter, cleaner alternative to Viper.
- Caarlos0/env: Strict struct tagging approach.
Anti-Patterns
- ❌ Hardcoded secrets — load all secrets from env vars or a secret manager
- ❌ Global config variables — return a typed Config struct and inject via constructors
- ❌ Starting without validation — crash immediately on missing required env vars