Issue-105 Add support of time.Duration in v.UnmarshalExact

This commit is contained in:
Yauhen Lazurkin 2016-09-23 23:32:50 +03:00
parent aebf0fcdc5
commit 8c1b961279

View file

@ -611,19 +611,7 @@ func (v *Viper) UnmarshalKey(key string, rawVal interface{}) error {
// on the fields of the structure are properly set. // on the fields of the structure are properly set.
func Unmarshal(rawVal interface{}) error { return v.Unmarshal(rawVal) } func Unmarshal(rawVal interface{}) error { return v.Unmarshal(rawVal) }
func (v *Viper) Unmarshal(rawVal interface{}) error { func (v *Viper) Unmarshal(rawVal interface{}) error {
config := &mapstructure.DecoderConfig{ err := decode(v.AllSettings(), defaultDecoderConfig(rawVal))
Metadata: nil,
Result: rawVal,
WeaklyTypedInput: true,
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
err = decoder.Decode(v.AllSettings())
if err != nil { if err != nil {
return err return err
@ -634,16 +622,19 @@ func (v *Viper) Unmarshal(rawVal interface{}) error {
return nil return nil
} }
// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality // defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot
// while erroring on non existing vals in the destination struct // of time.Duration values
func weakDecodeExact(input, output interface{}) error { func defaultDecoderConfig(output interface{}) *mapstructure.DecoderConfig {
config := &mapstructure.DecoderConfig{ return &mapstructure.DecoderConfig{
ErrorUnused: true,
Metadata: nil, Metadata: nil,
Result: output, Result: output,
WeaklyTypedInput: true, WeaklyTypedInput: true,
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
} }
}
// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
func decode(input interface{}, config *mapstructure.DecoderConfig) error {
decoder, err := mapstructure.NewDecoder(config) decoder, err := mapstructure.NewDecoder(config)
if err != nil { if err != nil {
return err return err
@ -654,7 +645,10 @@ func weakDecodeExact(input, output interface{}) error {
// Unmarshals the config into a Struct, erroring if a field is non-existant // Unmarshals the config into a Struct, erroring if a field is non-existant
// in the destination struct // in the destination struct
func (v *Viper) UnmarshalExact(rawVal interface{}) error { func (v *Viper) UnmarshalExact(rawVal interface{}) error {
err := weakDecodeExact(v.AllSettings(), rawVal) config := defaultDecoderConfig(rawVal)
config.ErrorUnused = true
err := decode(v.AllSettings(), config)
if err != nil { if err != nil {
return err return err