common/helpers: fix decoding of strings as slice

We use the previous version of the function from upstream.
This commit is contained in:
Vincent Bernat
2025-02-15 14:25:54 +01:00
parent e08331a286
commit e1672c7f32
2 changed files with 44 additions and 1 deletions

View File

@@ -36,12 +36,33 @@ func GetMapStructureDecoderConfig(config interface{}, hooks ...mapstructure.Deco
mapstructure.ComposeDecodeHookFunc(mapstructureUnmarshallerHookFuncs...),
mapstructure.TextUnmarshallerHookFunc(),
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
StringToSliceHookFunc(","),
),
),
}
}
// StringToSliceHookFunc returns a DecodeHookFunc that converts
// string to []string by splitting on the given sep.
func StringToSliceHookFunc(sep string) mapstructure.DecodeHookFunc {
return func(
f reflect.Kind,
t reflect.Kind,
data interface{},
) (interface{}, error) {
if f != reflect.String || t != reflect.Slice {
return data, nil
}
raw := data.(string)
if raw == "" {
return []string{}, nil
}
return strings.Split(raw, sep), nil
}
}
// ProtectedDecodeHookFunc wraps a DecodeHookFunc to recover and returns an error on panic.
func ProtectedDecodeHookFunc(hook mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (v interface{}, err error) {

View File

@@ -37,6 +37,28 @@ func TestMapStructureMatchName(t *testing.T) {
}
}
func TestStringToSliceHookFunc(t *testing.T) {
type Configuration struct {
A []string
B []int
}
TestConfigurationDecode(t, ConfigurationDecodeCases{
{
Initial: func() interface{} { return Configuration{} },
Configuration: func() interface{} {
return gin.H{
"a": "blip,blop",
"b": "1,2,3,4",
}
},
Expected: Configuration{
A: []string{"blip", "blop"},
B: []int{1, 2, 3, 4},
},
},
})
}
func TestProtectedDecodeHook(t *testing.T) {
var configuration struct {
A string