From 0c82789feb03da74b3390a5d64b8ce2ce9ba0f3e Mon Sep 17 00:00:00 2001 From: Lei Feng Date: Fri, 25 Dec 2015 12:29:33 +0800 Subject: [PATCH] Handle the case Get() returns either map[interface{}]interface{} or map[string]interface{} --- viper.go | 11 ++++++----- viper_test.go | 5 ++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/viper.go b/viper.go index 4a5b1eb..389a58e 100644 --- a/viper.go +++ b/viper.go @@ -526,13 +526,14 @@ func (v *Viper) Get(key string) interface{} { // Returns new Viper instance representing a sub tree of this instance func Sub(key string) *Viper { return v.Sub(key) } func (v *Viper) Sub(key string) *Viper { - data, ok := v.Get(key).(map[string]interface{}) - if !ok { + subv := New() + data := v.Get(key) + if reflect.TypeOf(data).Kind() == reflect.Map { + subv.config = cast.ToStringMap(data) + return subv + } else { return nil } - subv := New() - subv.config = data - return subv } // Returns the value associated with the key as a string diff --git a/viper_test.go b/viper_test.go index e9bb3f4..fcb9c4e 100644 --- a/viper_test.go +++ b/viper_test.go @@ -730,7 +730,10 @@ func TestSub(t *testing.T) { v.SetConfigType("yaml") 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")) subv = v.Sub("clothing.pants.size")