Skip to content

Values are not loaded from environment with SetDefaultsForZeroValuesOnly #364

@dlmartens

Description

@dlmartens

The change introduced in 2be9960 causes values to no longer load from the environment in the presence of SetDefaultsForZeroValuesOnly: true and a non-zero value for the corresponding field.

The following is a quick example to recreate the problem:

type Config struct {
	Username string `env:"USERNAME" envDefault:"admin"`
}
cfg := Config{Username: "root"}
err := env.ParseWithOptions(&cfg, env.Options{
	Environment:                  map[string]string{"USERNAME": "user1"},
	SetDefaultsForZeroValuesOnly: true,
})
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("%+v", cfg) // prints `{Username:root}`, but should print `{Username:user1}`

The relevant logic is here:

env/env.go

Lines 510 to 512 in 56a09d2

if value != "" && (!opts.SetDefaultsForZeroValuesOnly || refField.IsZero()) {
return set(refField, refTypeField, value, opts.FuncMap)
}

It does not check to ensure that value was loaded from envDefault rather than from the actual environment.

Thank you for the great library!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions