Go Envconfig
In this tutorial, you'll learn about Go envconfig: Struct Tags. We cover key concepts, practical examples, and best practices.
envconfig library -- Use envconfig to populate Go structs from environment variables using struct tags.
The Problem
envconfig maps env vars to struct fields via struct tags. The struct must be passed by pointer. Fields not exported or missing tags are skipped.
Wrong
type Config struct {
Port int
Host string
}
var cfg Config
envconfig.Process(&cfg) // Port=0, Host=""
Output:
// No struct tags. Env vars not mapped.
Right
type Config struct {
Port int `envconfig:"PORT" default:"8080"`
Host string `envconfig:"HOST" default:"localhost"`
}
var cfg Config
if err := envconfig.Process(&cfg); err != nil {
log.Fatal(err)
}
Output:
// PORT=9090 -> cfg.Port = 9090. Host defaults to localhost.
Prevention
- Use envconfig struct tags for env mapping
- Use default:"value" tag for defaults
- Use required:"true" to fail if missing
- Pass pointer to Process
- Supports custom decoders via Decode interface
Common Mistakes with envconfig
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro