Skip to content

Commit

Permalink
fix: passing prefix on anonymous struct (#205)
Browse files Browse the repository at this point in the history
  • Loading branch information
flaneur2020 committed Dec 30, 2021
1 parent 87131ff commit 66696b3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion env.go
Expand Up @@ -216,7 +216,7 @@ func doParse(ref reflect.Value, funcMap map[reflect.Type]ParserFunc, opts []Opti
continue
}
if reflect.Struct == refField.Kind() && refField.CanAddr() && refField.Type().Name() == "" {
if err := Parse(refField.Addr().Interface(), opts...); err != nil {
if err := Parse(refField.Addr().Interface(), optsWithPrefix(refType.Field(i), opts)...); err != nil {
return err
}
continue
Expand Down
32 changes: 32 additions & 0 deletions env_test.go
Expand Up @@ -124,6 +124,12 @@ type Config struct {
String string `env:"NONDEFINED_STR"`
}

NestedNonDefined struct {
NonDefined struct {
String string `env:"STR"`
} `envPrefix:"NONDEFINED_"`
} `envPrefix:"PRF_"`

NotAnEnv string
unexported string `env:"FOO"`
}
Expand Down Expand Up @@ -251,6 +257,7 @@ func TestParsesEnv(t *testing.T) {

nonDefinedStr := "nonDefinedStr"
os.Setenv("NONDEFINED_STR", nonDefinedStr)
os.Setenv("PRF_NONDEFINED_STR", nonDefinedStr)

cfg := Config{}
isNoErr(t, Parse(&cfg))
Expand Down Expand Up @@ -376,6 +383,7 @@ func TestParsesEnv(t *testing.T) {

isEqual(t, "postgres://localhost:5432/db", cfg.StringWithdefault)
isEqual(t, nonDefinedStr, cfg.NonDefined.String)
isEqual(t, nonDefinedStr, cfg.NestedNonDefined.NonDefined.String)

isEqual(t, str1, cfg.CustomSeparator[0])
isEqual(t, str2, cfg.CustomSeparator[1])
Expand Down Expand Up @@ -1390,6 +1398,30 @@ func TestPrefixPointers(t *testing.T) {
isEqual(t, "clean", cfg.Clean.Str)
}

func TestNestedPrefixPointer(t *testing.T) {
type ComplexConfig struct {
Foo struct {
Str string `env:"STR"`
} `envPrefix:"FOO_"`
}
cfg := ComplexConfig{}
isNoErr(t, Parse(&cfg, Options{Environment: map[string]string{"FOO_STR": "foo_str"}}))
isEqual(t, "foo_str", cfg.Foo.Str)

type ComplexConfig2 struct {
Foo struct {
Bar struct {
Str string `env:"STR"`
} `envPrefix:"BAR_"`
Bar2 string `env:"BAR2"`
} `envPrefix:"FOO_"`
}
cfg2 := ComplexConfig2{}
isNoErr(t, Parse(&cfg2, Options{Environment: map[string]string{"FOO_BAR_STR": "kek", "FOO_BAR2": "lel"}}))
isEqual(t, "lel", cfg2.Foo.Bar2)
isEqual(t, "kek", cfg2.Foo.Bar.Str)
}

func TestComplePrefix(t *testing.T) {
type Config struct {
Home string `env:"HOME"`
Expand Down

0 comments on commit 66696b3

Please sign in to comment.