fix: Viper.Sub() Arrays not supported

This commit is contained in:
kayLeeo 2022-07-23 15:25:15 +08:00
parent 5247643f02
commit d6b9754a87
2 changed files with 17 additions and 1 deletions

View file

@ -939,9 +939,22 @@ func (v *Viper) Sub(key string) *Viper {
return nil
}
if reflect.TypeOf(data).Kind() == reflect.Map {
//if t := reflect.TypeOf(data).Kind(); t == reflect.Map || t == reflect.Slice {
// // https://github.com/spf13/cast/pull/148
// subv.config = cast.ToStringMap(data)
// return subv
//}
switch reflect.TypeOf(data).Kind() {
case reflect.Map:
subv.config = cast.ToStringMap(data)
return subv
case reflect.Slice, reflect.Array:
dataValue := reflect.ValueOf(data)
subv.config = make(map[string]interface{}, dataValue.Len())
for x := 0; x < dataValue.Len(); x++ {
subv.config[cast.ToString(x)] = dataValue.Index(x).Interface()
}
return subv
}
return nil
}

View file

@ -1500,6 +1500,9 @@ func TestSub(t *testing.T) {
subv = v.Sub("missing.key")
assert.Equal(t, (*Viper)(nil), subv)
subv = v.Sub("hobbies")
assert.Equal(t, v.Get("hobbies.0"), subv.Get("0"))
}
var hclWriteExpected = []byte(`"foos" = {