From 0f77fefcf68e63b1d9bc693e01b182e84fabbd30 Mon Sep 17 00:00:00 2001 From: NithinGudla <47893203+NithinGudla@users.noreply.github.com> Date: Tue, 30 Apr 2024 17:56:10 +0530 Subject: [PATCH] fix: add logic to handle nil pointer structs (#306) --- env.go | 13 +++++++++++++ env_test.go | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/env.go b/env.go index d73ae09..d4bdf55 100644 --- a/env.go +++ b/env.go @@ -300,6 +300,15 @@ func doParseField(refField reflect.Value, refTypeField reflect.StructField, proc return err } + if isStructPtr(refField) && refField.IsNil() { + refField.Set(reflect.New(refField.Type().Elem())) + refField = refField.Elem() + } + + if _, ok := opts.FuncMap[refField.Type()]; ok { + return nil + } + if reflect.Struct == refField.Kind() { return doParse(refField, processField, optionsWithEnvPrefix(refTypeField, opts)) } @@ -644,3 +653,7 @@ func parseTextUnmarshalers(field reflect.Value, data []string, sf reflect.Struct func ToMap(env []string) map[string]string { return toMap(env) } + +func isStructPtr(v reflect.Value) bool { + return reflect.Ptr == v.Kind() && v.Type().Elem().Kind() == reflect.Struct +} diff --git a/env_test.go b/env_test.go index eb8d08c..e9fd37c 100644 --- a/env_test.go +++ b/env_test.go @@ -595,6 +595,15 @@ func TestParsesEnvInner(t *testing.T) { isEqual(t, uint(8), cfg.InnerStruct.Number) } +func TestParsesEnvInner_WhenInnerStructPointerIsNil(t *testing.T) { + t.Setenv("innervar", "someinnervalue") + t.Setenv("innernum", "8") + cfg := ParentStruct{} + isNoErr(t, Parse(&cfg)) + isEqual(t, "someinnervalue", cfg.InnerStruct.Inner) + isEqual(t, uint(8), cfg.InnerStruct.Number) +} + func TestParsesEnvInnerFails(t *testing.T) { type config struct { Foo struct {