How to Use envconfig for Struct-Based Configuration in Go

Use envconfig to load environment variables into a Go struct by defining fields with env tags and calling Process.

You use envconfig by defining a struct with struct tags that map environment variables to fields, then calling envconfig.Process to populate it. The library reads the environment, parses values, and assigns them to the struct fields based on the env tag key.

package main

import (
	"github.com/kelseyhightower/envconfig"
)

type Config struct {
	DatabaseHost string `env:"DATABASE_HOST"`
	DatabasePort int    `env:"DATABASE_PORT"`
	Debug        bool   `env:"DEBUG"`
}

func main() {
	var config Config
	if err := envconfig.Process("", &config); err != nil {
		panic(err)
	}
	// Use config.DatabaseHost, etc.
}

Set the environment variables before running your program:

export DATABASE_HOST=localhost
export DATABASE_PORT=5432
export DEBUG=true

The envconfig.Process function reads these variables and fills the Config struct. If a variable is missing and no default is set, the field remains at its zero value.