mirror of
https://github.com/akvorado/akvorado.git
synced 2025-12-12 06:24:10 +01:00
common/helpers: fix decoding of strings as slice
We use the previous version of the function from upstream.
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user