mirror of
https://github.com/spf13/viper
synced 2024-12-22 03:27:03 +00:00
fix: add back weak string slice hook
Signed-off-by: Mark Sagi-Kazar <mark.sagikazar@gmail.com>
This commit is contained in:
parent
c019486d56
commit
5ce200a311
1 changed files with 24 additions and 1 deletions
25
viper.go
25
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,28 @@ func defaultDecoderConfig(output any, opts ...DecoderConfigOption) *mapstructure
|
|||
return c
|
||||
}
|
||||
|
||||
// As of mapstructure v2.0.0 StringToSliceHookFunc checks if the return type is a string slice.
|
||||
// This function removes that check.
|
||||
// TODO: implement a function that checks if the value can be converted to the return type and use it instead.
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
|
|
Loading…
Reference in a new issue