Environment configuration
Read environment variables at the boundary, validate them early, and keep configuration loading separate from business logic.
Canonical guidance
- load config once near startup
- validate required settings early
- pass typed config inward
Use when
- startup wiring
- deployment-specific configuration
- selecting ports, DSNs, timeouts, and feature flags
Avoid
- calling
os.Getenvfrom deep business logic - treating empty string as a valid default accidentally
- mixing parsing, validation, and application behavior in one huge
main
Preferred pattern
- parse environment and flags into a config struct, validate it, then pass it to constructors
Anti-pattern
- hidden package globals initialized from the environment on first use
Explanation: This is tempting because it reduces wiring, but it makes configuration harder to test, validate, and reason about.
Why
- configuration is cleaner when it stays a boundary concern
Related pages
Sources
- os package - Go Team
- flag package - Go Team