Skip to content

Commit

Permalink
fix: error in embedded struct when using option RequiredIfNoDef:true (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
bhallionOhbibi committed Sep 6, 2021
1 parent a670257 commit ba5c1ad
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion env.go
Expand Up @@ -270,7 +270,7 @@ func get(field reflect.StructField, opts []Options) (val string, err error) {
defer os.Unsetenv(key)
}

if required && !exists {
if required && !exists && len(key) > 0 {
return "", fmt.Errorf(`env: required environment variable %q is not set`, key)
}

Expand Down
8 changes: 8 additions & 0 deletions env_test.go
Expand Up @@ -1377,18 +1377,26 @@ func TestCustomTimeParser(t *testing.T) {
}

func TestRequiredIfNoDefOption(t *testing.T) {
type Tree struct {
Fruit string `env:"FRUIT"`
}
type config struct {
Name string `env:"NAME"`
Genre string `env:"GENRE" envDefault:"Unknown"`
Tree
}
var cfg config

t.Run("missing", func(t *testing.T) {
isErrorWithMessage(t, Parse(&cfg, Options{RequiredIfNoDef: true}), `env: required environment variable "NAME" is not set`)
os.Setenv("NAME", "John")
t.Cleanup(os.Clearenv)
isErrorWithMessage(t, Parse(&cfg, Options{RequiredIfNoDef: true}), `env: required environment variable "FRUIT" is not set`)
})

t.Run("all set", func(t *testing.T) {
os.Setenv("NAME", "John")
os.Setenv("FRUIT", "Apple")
t.Cleanup(os.Clearenv)

// should not trigger an error for the missing 'GENRE' env because it has a default value.
Expand Down

0 comments on commit ba5c1ad

Please sign in to comment.