From 090342a4130da79457e942869f1b71d82d340ed8 Mon Sep 17 00:00:00 2001 From: aler9 <46489434+aler9@users.noreply.github.com> Date: Fri, 30 Dec 2022 18:40:27 +0100 Subject: [PATCH] conf: allow to set empty slices with empty env variables --- internal/conf/env.go | 6 +++++- internal/conf/env_test.go | 19 ++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/internal/conf/env.go b/internal/conf/env.go index f6c8aab3..0182e1ce 100644 --- a/internal/conf/env.go +++ b/internal/conf/env.go @@ -135,7 +135,11 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err case reflect.Slice: if rt.Elem() == reflect.TypeOf("") { if ev, ok := env[prefix]; ok { - rv.Set(reflect.ValueOf(strings.Split(ev, ","))) + if ev == "" { + rv.Set(reflect.ValueOf([]string{})) + } else { + rv.Set(reflect.ValueOf(strings.Split(ev, ","))) + } } return nil } diff --git a/internal/conf/env_test.go b/internal/conf/env_test.go index 384e5ab0..db5ed3a4 100644 --- a/internal/conf/env_test.go +++ b/internal/conf/env_test.go @@ -18,13 +18,14 @@ type mapEntry struct { } type testStruct struct { - MyString string - MyInt int - MyFloat float64 - MyBool bool - MyDuration StringDuration - MyMap map[string]*mapEntry - MySlice []string + MyString string + MyInt int + MyFloat float64 + MyBool bool + MyDuration StringDuration + MyMap map[string]*mapEntry + MySlice []string + MySliceEmpty []string } func TestEnvironment(t *testing.T) { @@ -55,6 +56,9 @@ func TestEnvironment(t *testing.T) { os.Setenv("MYPREFIX_MYSLICE", "val1,val2") defer os.Unsetenv("MYPREFIX_MYSLICE") + os.Setenv("MYPREFIX_MYSLICEEMPTY", "") + defer os.Unsetenv("MYPREFIX_MYSLICEEMPTY") + var s testStruct err := loadFromEnvironment("MYPREFIX", &s) require.NoError(t, err) @@ -74,4 +78,5 @@ func TestEnvironment(t *testing.T) { require.Equal(t, 456, v.MyStruct.MyParam) require.Equal(t, []string{"val1", "val2"}, s.MySlice) + require.Equal(t, []string{}, s.MySliceEmpty) }