From c254a5ba545ed40ffe93e8a2a1d6a09a3c2c60cc Mon Sep 17 00:00:00 2001 From: Herkermer Sherwood Date: Sat, 29 Apr 2017 14:28:30 -0700 Subject: [PATCH] Add parallel functions/methods to unmarshal data and return mapstructure.Metadata This was not added for UnmarshalExact, since all keys should be used and none left unused. --- viper.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/viper.go b/viper.go index 5377ddc..ac98754 100644 --- a/viper.go +++ b/viper.go @@ -731,6 +731,27 @@ func (v *Viper) UnmarshalKey(key string, rawVal interface{}) error { return nil } +// UnmarshalKeyWithMeta performs UnmarshalKey and using an additional +// parameter, also provides access to the mapstructure.Metadata. +func UnmarshalKeyWithMeta(key string, rawVal interface{}) (mapstructure.Metadata, error) { + return v.UnmarshalKeyWithMeta(key, rawVal) +} +func (v *Viper) UnmarshalKeyWithMeta(key string, rawVal interface{}) (mapstructure.Metadata, error) { + var meta mapstructure.Metadata + config := defaultDecoderConfig(rawVal) + config.Metadata = &meta + + err := decode(v.Get(key), config) + + if err != nil { + return meta, err + } + + v.insensitiviseMaps() + + return meta, nil +} + // Unmarshal unmarshals the config into a Struct. Make sure that the tags // on the fields of the structure are properly set. func Unmarshal(rawVal interface{}) error { return v.Unmarshal(rawVal) } @@ -746,6 +767,27 @@ func (v *Viper) Unmarshal(rawVal interface{}) error { return nil } +// UnmarshalWithMeta performs Unmarshal and using an additional +// parameter, also provides access to the mapstructure.Metadata. +func UnmarshalWithMeta(rawVal interface{}) (mapstructure.Metadata, error) { + return v.UnmarshalWithMeta(rawVal) +} +func (v *Viper) UnmarshalWithMeta(rawVal interface{}) (mapstructure.Metadata, error) { + var meta mapstructure.Metadata + config := defaultDecoderConfig(rawVal) + config.Metadata = &meta + + err := decode(v.AllSettings(), config) + + if err != nil { + return meta, err + } + + v.insensitiviseMaps() + + return meta, nil +} + // defaultDecoderConfig returns default mapsstructure.DecoderConfig with support // of time.Duration values func defaultDecoderConfig(output interface{}) *mapstructure.DecoderConfig {