Skip to content

Commit

Permalink
fix: custom parsers with anon inner structs (#227)
Browse files Browse the repository at this point in the history
* fix: custom parsers with anon inner structs

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>

* test: improve test

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>

* test: improve test

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
caarlos0 committed May 30, 2022
1 parent 512d9f8 commit a5d7cf5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
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

0 comments on commit a5d7cf5

Please sign in to comment.