Browse Source

conf: allow to set empty slices with empty env variables

pull/1364/head
aler9 4 years ago
parent
commit
090342a413
  1. 6
      internal/conf/env.go
  2. 19
      internal/conf/env_test.go

6
internal/conf/env.go

@ -135,7 +135,11 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
case reflect.Slice: case reflect.Slice:
if rt.Elem() == reflect.TypeOf("") { if rt.Elem() == reflect.TypeOf("") {
if ev, ok := env[prefix]; ok { 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 return nil
} }

19
internal/conf/env_test.go

@ -18,13 +18,14 @@ type mapEntry struct {
} }
type testStruct struct { type testStruct struct {
MyString string MyString string
MyInt int MyInt int
MyFloat float64 MyFloat float64
MyBool bool MyBool bool
MyDuration StringDuration MyDuration StringDuration
MyMap map[string]*mapEntry MyMap map[string]*mapEntry
MySlice []string MySlice []string
MySliceEmpty []string
} }
func TestEnvironment(t *testing.T) { func TestEnvironment(t *testing.T) {
@ -55,6 +56,9 @@ func TestEnvironment(t *testing.T) {
os.Setenv("MYPREFIX_MYSLICE", "val1,val2") os.Setenv("MYPREFIX_MYSLICE", "val1,val2")
defer os.Unsetenv("MYPREFIX_MYSLICE") defer os.Unsetenv("MYPREFIX_MYSLICE")
os.Setenv("MYPREFIX_MYSLICEEMPTY", "")
defer os.Unsetenv("MYPREFIX_MYSLICEEMPTY")
var s testStruct var s testStruct
err := loadFromEnvironment("MYPREFIX", &s) err := loadFromEnvironment("MYPREFIX", &s)
require.NoError(t, err) require.NoError(t, err)
@ -74,4 +78,5 @@ func TestEnvironment(t *testing.T) {
require.Equal(t, 456, v.MyStruct.MyParam) require.Equal(t, 456, v.MyStruct.MyParam)
require.Equal(t, []string{"val1", "val2"}, s.MySlice) require.Equal(t, []string{"val1", "val2"}, s.MySlice)
require.Equal(t, []string{}, s.MySliceEmpty)
} }

Loading…
Cancel
Save