Handle the case Get() returns either map[interface{}]interface{} or map[string]interface{}

This commit is contained in:
Lei Feng 2015-12-25 12:29:33 +08:00
parent 110492b300
commit 0c82789feb
2 changed files with 10 additions and 6 deletions

View File

@ -526,13 +526,14 @@ func (v *Viper) Get(key string) interface{} {
// Returns new Viper instance representing a sub tree of this instance // Returns new Viper instance representing a sub tree of this instance
func Sub(key string) *Viper { return v.Sub(key) } func Sub(key string) *Viper { return v.Sub(key) }
func (v *Viper) Sub(key string) *Viper { func (v *Viper) Sub(key string) *Viper {
data, ok := v.Get(key).(map[string]interface{}) subv := New()
if !ok { data := v.Get(key)
if reflect.TypeOf(data).Kind() == reflect.Map {
subv.config = cast.ToStringMap(data)
return subv
} else {
return nil return nil
} }
subv := New()
subv.config = data
return subv
} }
// Returns the value associated with the key as a string // Returns the value associated with the key as a string

View File

@ -730,7 +730,10 @@ func TestSub(t *testing.T) {
v.SetConfigType("yaml") v.SetConfigType("yaml")
v.ReadConfig(bytes.NewBuffer(yamlExample)) v.ReadConfig(bytes.NewBuffer(yamlExample))
subv := v.Sub("clothing.pants") subv := v.Sub("clothing")
assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("pants.size"))
subv = v.Sub("clothing.pants")
assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("size")) assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("size"))
subv = v.Sub("clothing.pants.size") subv = v.Sub("clothing.pants.size")