Browse Source

conf: allow to set empty slices with empty env variables

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

4
internal/conf/env.go

@ -135,8 +135,12 @@ 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 {
if ev == "" {
rv.Set(reflect.ValueOf([]string{}))
} else {
rv.Set(reflect.ValueOf(strings.Split(ev, ","))) rv.Set(reflect.ValueOf(strings.Split(ev, ",")))
} }
}
return nil return nil
} }
} }

5
internal/conf/env_test.go

@ -25,6 +25,7 @@ type testStruct struct {
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