Apply environment
Use a prefix to keep CLI configuration separate from other process variables:
type Database struct {
Driver string
MaxOpenConns int
}
type CLIConfig struct {
DB *Database `env:"DB"`
}
// E2ENGINE_DB_DRIVER=postgres
// E2ENGINE_DB_MAXOPENCONNS=8
binding, err := model.NewBinding[CLIConfig](
model.WithEnvPrefix("E2ENGINE"),
)
if err != nil {
return err
}
cfg := CLIConfig{}
if err := binding.ApplyEnv(&cfg); err != nil {
return err
}
NewBinding snapshots matching process variables. Changing an environment variable after construction does not change that binding's ApplyEnv result. Present values overwrite existing fields. Call ApplyDefaults first when environment values should override literal defaults; ValidateWithDefaults performs defaults, environment, then validation in that order.
For each field, an explicit env tag supplies its path segment; otherwise a json tag name is used, then the exported Go field name. Segments are uppercased and joined with underscores. env:"-" and json:"-" disable environment traversal for a field and its children. Explicit child names are still joined to the parent path.
Indexed variables can populate a slice of structs:
type Endpoint struct {
URL string
}
type Runner struct {
Endpoints []Endpoint
}
// E2ENGINE_RUNNER_ENDPOINTS_0_URL=https://runner.example
// E2ENGINE_RUNNER_ENDPOINTS_1_URL=https://backup.example
The largest indexed struct slice has 1,024 elements by default. Set a different positive limit with model.WithMaxEnvSliceLength(n); an index outside that limit returns an error before that slice grows. Environment application is not transactional, so earlier fields may already have changed if a later field fails.