Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: error in embedded struct when using option RequiredIfNoDef:true #191

Merged
merged 1 commit into from Sep 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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