Documentation
¶
Overview ¶
The parsenv package exposes a Load function that populates the fields of a struct with data from environment variables.
var myConfig struct {
foo string `env:"required"`
bar int `env:"default=15"`
baz float64 `env:"name=bAz;default=6.97"`
qux bool `env:"-"`
}
if err := parsenv.Load(&myConfig); err != nil {
log.Fatal(err)
}
Per default, field names are converted from PascalCase or camelCase to SCREAMING_SNAKE_CASE.
For parsing options refer to the documentation of parsenv.TagData.
Supported types are string, int, bool, float64, and any custom type implementing the EnvParser interface.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Load ¶
Load reads environment variables into a struct. If the `env` variable passed is not a pointer to a struct, Load will panic. If any of the fields contain invalid `env` struct tags, Load will panic also. If one or more fields marked as 'required' don't have a corresponding environment variable, Load will return an error.
Example ¶
os.Setenv("FOO", "こんにちは、世界!")
os.Setenv("BAZ", "13.37")
os.Setenv("QUX", "yes")
var myConfig struct {
foo string `env:"required"`
bar int `env:"default=15"`
baz float64 `env:"name=bAz;default=6.97"`
qux bool
}
if err := Load(&myConfig); err != nil {
log.Fatal(err)
}
// because BAZ does not match the custom name bAz, the default value is applied.
fmt.Println(myConfig.foo, myConfig.bar, myConfig.baz, myConfig.qux)
Output: こんにちは、世界! 15 6.97 true
Types ¶
type EnvParser ¶
Any custom type appearing as a non-ignored field in a struct passed to Load must implement a ParseEnv method. ParseEnv must take a pointer receiver.
type TagData ¶
type TagData struct {
Name string // name=<name>
Default string // default=<value>
Required bool // required
Ignored bool // -
}
The behavior of how the environment is read into a struct can be influenced with the `env` struct tag.
var myConfig struct{
foo int `env:"-"` // ignore this field
bar float64 `env:"required"` // return an error if BAR is not found in the environment
baz bool `env:"name=baz"` // specify a custom name for the env var (per default the field name is converted to SCREAMING_SNAKE_CASE)
zap string `env:"default=hello world"` // specify a default value
puf int `env:"name=PUFF;default=19"` // use ; to specify multiple properties
}