This commit is contained in:
kaylee 2023-11-30 16:58:34 +02:00 committed by GitHub
commit f2a0ab2ff7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 1 deletions

View file

@ -956,13 +956,25 @@ func (v *Viper) Sub(key string) *Viper {
return nil
}
if reflect.TypeOf(data).Kind() == reflect.Map {
switch reflect.TypeOf(data).Kind() {
case reflect.Map:
subv.parents = append(v.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix
subv.envKeyReplacer = v.envKeyReplacer
subv.config = cast.ToStringMap(data)
return subv
case reflect.Slice, reflect.Array:
subv.parents = append(v.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix
subv.envKeyReplacer = v.envKeyReplacer
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

@ -1536,6 +1536,10 @@ 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"))
subv = v.Sub("clothing")
assert.Equal(t, []string{"clothing"}, subv.parents)