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 non empty struct pointer value #236

Merged
merged 1 commit into from
Sep 12, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 2 additions & 6 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,12 +226,8 @@ func doParseField(refField reflect.Value, refTypeField reflect.StructField, func
if !refField.CanSet() {
return nil
}
if reflect.Ptr == refField.Kind() && !refField.IsNil() {
if refField.Elem().Kind() == reflect.Struct {
return ParseWithFuncs(refField.Interface(), funcMap, optsWithPrefix(refTypeField, opts)...)
}

return ParseWithFuncs(refField.Interface(), funcMap, opts...)
if reflect.Ptr == refField.Kind() && refField.Elem().Kind() == reflect.Struct {
return ParseWithFuncs(refField.Interface(), funcMap, optsWithPrefix(refTypeField, opts)...)
}
if reflect.Struct == refField.Kind() && refField.CanAddr() && refField.Type().Name() == "" {
return ParseWithFuncs(refField.Addr().Interface(), funcMap, optsWithPrefix(refTypeField, opts)...)
Expand Down
46 changes: 46 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1475,6 +1475,52 @@ func TestComplePrefix(t *testing.T) {
isEqual(t, "blahhh", cfg.Blah)
}

func TestNonStructPtrValues(t *testing.T) {
type Foo struct {
FltPtr *float64 `env:"FLT_PRT"`
}

type ComplexConfig struct {
StrPtr *string `env:"STR_PTR"`
Foo Foo `env:"FOO_"`
}

cfg1 := ComplexConfig{}

isNoErr(t, Parse(&cfg1))
isEqual(t, nil, cfg1.StrPtr)
isEqual(t, nil, cfg1.Foo.FltPtr)

strPtr := "str_ptr"
fltPtr := 3.16
cfg2 := ComplexConfig{
StrPtr: &strPtr,
Foo: Foo{
FltPtr: &fltPtr,
},
}

setEnv(t, "STR_PTR", "env_str_ptr")
setEnv(t, "FLT_PRT", "5.16")

isNoErr(t, Parse(&cfg2))
isEqual(t, "env_str_ptr", *cfg2.StrPtr)
isEqual(t, 5.16, *cfg2.Foo.FltPtr)

var strPtrNill *string
var fltPtrNill *float64
cfg3 := ComplexConfig{
StrPtr: strPtrNill,
Foo: Foo{
FltPtr: fltPtrNill,
},
}

isNoErr(t, Parse(&cfg3))
isEqual(t, "env_str_ptr", *cfg3.StrPtr)
isEqual(t, 5.16, *cfg3.Foo.FltPtr)
}

func isTrue(tb testing.TB, b bool) {
tb.Helper()

Expand Down