Skip to content

Go Envconfig

DodaTech 1 min read

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.
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

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. 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

**How to handle slices?**

Use envconfig:"LIST" with space or comma-separated values.

Can I use prefixes?

Yes. envconfig.ProcessWith(&cfg, envconfig.Options{Prefix: "APP_"}).

Does envconfig support nested structs?

Yes. Flattened with prefix from parent.


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