Skip to content

Commit f3ddf1f

Browse files
akutuevAlexander Kutuev
andauthored
fix: non empty struct pointer value (#236)
Co-authored-by: Alexander Kutuev <[email protected]>
1 parent 69c7b5a commit f3ddf1f

File tree

2 files changed

+48
-6
lines changed

2 files changed

+48
-6
lines changed

env.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,12 +226,8 @@ func doParseField(refField reflect.Value, refTypeField reflect.StructField, func
226226
if !refField.CanSet() {
227227
return nil
228228
}
229-
if reflect.Ptr == refField.Kind() && !refField.IsNil() {
230-
if refField.Elem().Kind() == reflect.Struct {
231-
return ParseWithFuncs(refField.Interface(), funcMap, optsWithPrefix(refTypeField, opts)...)
232-
}
233-
234-
return ParseWithFuncs(refField.Interface(), funcMap, opts...)
229+
if reflect.Ptr == refField.Kind() && refField.Elem().Kind() == reflect.Struct {
230+
return ParseWithFuncs(refField.Interface(), funcMap, optsWithPrefix(refTypeField, opts)...)
235231
}
236232
if reflect.Struct == refField.Kind() && refField.CanAddr() && refField.Type().Name() == "" {
237233
return ParseWithFuncs(refField.Addr().Interface(), funcMap, optsWithPrefix(refTypeField, opts)...)

env_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1475,6 +1475,52 @@ func TestComplePrefix(t *testing.T) {
14751475
isEqual(t, "blahhh", cfg.Blah)
14761476
}
14771477

1478+
func TestNonStructPtrValues(t *testing.T) {
1479+
type Foo struct {
1480+
FltPtr *float64 `env:"FLT_PRT"`
1481+
}
1482+
1483+
type ComplexConfig struct {
1484+
StrPtr *string `env:"STR_PTR"`
1485+
Foo Foo `env:"FOO_"`
1486+
}
1487+
1488+
cfg1 := ComplexConfig{}
1489+
1490+
isNoErr(t, Parse(&cfg1))
1491+
isEqual(t, nil, cfg1.StrPtr)
1492+
isEqual(t, nil, cfg1.Foo.FltPtr)
1493+
1494+
strPtr := "str_ptr"
1495+
fltPtr := 3.16
1496+
cfg2 := ComplexConfig{
1497+
StrPtr: &strPtr,
1498+
Foo: Foo{
1499+
FltPtr: &fltPtr,
1500+
},
1501+
}
1502+
1503+
setEnv(t, "STR_PTR", "env_str_ptr")
1504+
setEnv(t, "FLT_PRT", "5.16")
1505+
1506+
isNoErr(t, Parse(&cfg2))
1507+
isEqual(t, "env_str_ptr", *cfg2.StrPtr)
1508+
isEqual(t, 5.16, *cfg2.Foo.FltPtr)
1509+
1510+
var strPtrNill *string
1511+
var fltPtrNill *float64
1512+
cfg3 := ComplexConfig{
1513+
StrPtr: strPtrNill,
1514+
Foo: Foo{
1515+
FltPtr: fltPtrNill,
1516+
},
1517+
}
1518+
1519+
isNoErr(t, Parse(&cfg3))
1520+
isEqual(t, "env_str_ptr", *cfg3.StrPtr)
1521+
isEqual(t, 5.16, *cfg3.Foo.FltPtr)
1522+
}
1523+
14781524
func isTrue(tb testing.TB, b bool) {
14791525
tb.Helper()
14801526

0 commit comments

Comments
 (0)