initialize struct from env vars (golang)
Go 100%

README.md

initialize struct from environment variables #

This is a very straightforward library; it initializes each exported field in a struct from an environment variable. Usage:

import "go.vedthiru.com/envstruct"

type logOpts struct {
	File    string `envDefault:"./log"`
	UseJSON bool
}
type testStruct struct {
	Port    uint
	BufSize uint
	Log     logOpts
	Custom  string `envVar:"MY_VAR"`
	IP      net.IP
}

func main() {
  var c config
  err := envstruct.Parse("MY_APP", &c)
}
  • If a field doesn't have the tag envVar, Parse reads the value from an appropriate corresponding environment variable. If the struct is nested, the names of the intermediate fields are added. For example, UseJSON above is read from MY_APP_LOG_USE_JSON.
  • envstruct supports parsing strings, uints, bools, and any type that implements encoding.TextUnmarshaler.
  • envstruct will only handle fields exported from the struct (just like encoding/json and encoding/xml).
  • If a field does not have the envDefault struct tag, and the environment variable is not defined, Parse will return an error.