Something went wrong. Try again.
initialize struct from env vars (golang)
Something went wrong. Try again.
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,Parsereads the value from an appropriate corresponding environment variable. If the struct is nested, the names of the intermediate fields are added. For example,UseJSONabove is read fromMY_APP_LOG_USE_JSON. - envstruct supports parsing
strings,uints,bools, and any type that implementsencoding.TextUnmarshaler. - envstruct will only handle fields exported from the struct (just like
encoding/jsonandencoding/xml). - If a field does not have the
envDefaultstruct tag, and the environment variable is not defined,Parsewill return an error.