From 5d46e70da8c0b6f812e0b170b7a985753b5c63cb Mon Sep 17 00:00:00 2001 From: Miguel Eduardo Gil Biraud Date: Mon, 10 Apr 2017 11:26:50 +0200 Subject: [PATCH] Fix UnmarshalKey handling of time.Duration * Failing test for key unmarshaling with nested structs containing time.Duration * Fix UnmarshalKey to use of defaultDecoderConfig --- viper.go | 10 +++++++++- viper_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/viper.go b/viper.go index 22a2ed8..5ca66ae 100644 --- a/viper.go +++ b/viper.go @@ -719,7 +719,15 @@ func (v *Viper) GetSizeInBytes(key string) uint { // UnmarshalKey takes a single key and unmarshals it into a Struct. func UnmarshalKey(key string, rawVal interface{}) error { return v.UnmarshalKey(key, rawVal) } func (v *Viper) UnmarshalKey(key string, rawVal interface{}) error { - return mapstructure.Decode(v.Get(key), rawVal) + err := decode(v.Get(key), defaultDecoderConfig(rawVal)) + + if err != nil { + return err + } + + v.insensitiviseMaps() + + return nil } // Unmarshal unmarshals the config into a Struct. Make sure that the tags diff --git a/viper_test.go b/viper_test.go index cd7b65c..cd10603 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1102,6 +1102,35 @@ func TestCaseInsensitiveSet(t *testing.T) { } } +func TestParseNested(t *testing.T) { + type duration struct { + Delay time.Duration + } + + type item struct { + Name string + Delay time.Duration + Nested duration + } + + config := `[[parent]] + delay="100ms" + [parent.nested] + delay="200ms" +` + initConfig("toml", config) + + var items []item + err := v.UnmarshalKey("parent", &items) + if err != nil { + t.Fatalf("unable to decode into struct, %v", err) + } + + assert.Equal(t, 1, len(items)) + assert.Equal(t, 100*time.Millisecond, items[0].Delay) + assert.Equal(t, 200*time.Millisecond, items[0].Nested.Delay) +} + func doTestCaseInsensitive(t *testing.T, typ, config string) { initConfig(typ, config) Set("RfD", true)