StringToSliceHookFunc
diff --git a/decode_hooks.go b/decode_hooks.go new file mode 100644 index 0000000..1321ba1 --- /dev/null +++ b/decode_hooks.go
@@ -0,0 +1,22 @@ +package mapstructure + +import ( + "reflect" + "strings" +) + +// StringToSliceHookFunc returns a DecodeHookFunc that converts +// string to []string by splitting on the given sep. +func StringToSliceHookFunc(sep string) 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) + return strings.Split(raw, sep), nil + } +}
diff --git a/decode_hooks_test.go b/decode_hooks_test.go new file mode 100644 index 0000000..2e22e22 --- /dev/null +++ b/decode_hooks_test.go
@@ -0,0 +1,39 @@ +package mapstructure + +import ( + "reflect" + "testing" +) + +func TestStringToSliceHookFunc(t *testing.T) { + f := StringToSliceHookFunc(",") + + cases := []struct { + f, t reflect.Kind + data interface{} + result interface{} + err bool + }{ + {reflect.Slice, reflect.Slice, 42, 42, false}, + {reflect.String, reflect.String, 42, 42, false}, + { + reflect.String, + reflect.Slice, + "foo,bar,baz", + []string{"foo", "bar", "baz"}, + false, + }, + } + + for i, tc := range cases { + actual, err := f(tc.f, tc.t, tc.data) + if tc.err != (err != nil) { + t.Fatalf("case %d: expected err %#v", i, tc.err) + } + if !reflect.DeepEqual(actual, tc.result) { + t.Fatalf( + "case %d: expected %#v, got %#v", + i, tc.result, actual) + } + } +}