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: custom parsers with anon inner structs #227

Merged
merged 3 commits into from
May 30, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion env.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,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(), optsWithPrefix(refType.Field(i), opts)...); err != nil {
if err := ParseWithFuncs(refField.Addr().Interface(), funcMap, optsWithPrefix(refType.Field(i), opts)...); err != nil {
return err
}
continue
Expand Down
28 changes: 28 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,34 @@ func TestCustomParser(t *testing.T) {
}
}

func TestIssue226(t *testing.T) {
type config struct {
Inner struct {
Abc []byte `env:"ABC" envDefault:"asdasd"`
Def []byte `env:"DEF" envDefault:"a"`
}
Hij []byte `env:"HIJ"`
Lmn []byte `env:"LMN"`
}

setEnv(t, "HIJ", "a")
setEnv(t, "LMN", "b")

cfg := &config{}
isNoErr(t, ParseWithFuncs(cfg, map[reflect.Type]ParserFunc{
reflect.TypeOf([]byte{0}): func(v string) (interface{}, error) {
if v == "a" {
return []byte("nope"), nil
}
return []byte(v), nil
},
}))
isEqual(t, cfg.Inner.Abc, []byte("asdasd"))
isEqual(t, cfg.Inner.Def, []byte("nope"))
isEqual(t, cfg.Hij, []byte("nope"))
isEqual(t, cfg.Lmn, []byte("b"))
}

func TestParseWithFuncsNoPtr(t *testing.T) {
type foo struct{}
isErrorWithMessage(t, ParseWithFuncs(foo{}, nil), "env: expected a pointer to a Struct")
Expand Down