diff --git a/viper.go b/viper.go index e18ddde38b..548aca7b04 100644 --- a/viper.go +++ b/viper.go @@ -1158,7 +1158,8 @@ func defaultDecoderConfig(output any, opts ...DecoderConfigOption) *mapstructure WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( mapstructure.StringToTimeDurationHookFunc(), - mapstructure.StringToSliceHookFunc(","), + // mapstructure.StringToSliceHookFunc(","), + stringToWeakSliceHookFunc(","), ), } for _, opt := range opts { @@ -1167,6 +1168,30 @@ func defaultDecoderConfig(output any, opts ...DecoderConfigOption) *mapstructure return c } +// StringToSliceHookFunc returns a DecodeHookFunc that converts +// string to []string by splitting on the given sep. +func stringToWeakSliceHookFunc(sep string) mapstructure.DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Slice { + return data, nil + } + // if t != reflect.SliceOf(f) { + // return data, nil + // } + + raw := data.(string) + if raw == "" { + return []string{}, nil + } + + return strings.Split(raw, sep), nil + } +} + // decode is a wrapper around mapstructure.Decode that mimics the WeakDecode functionality. func decode(input any, config *mapstructure.DecoderConfig) error { decoder, err := mapstructure.NewDecoder(config)