Skip to content

Commit

Permalink
StringToSliceHookFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Apr 27, 2014
1 parent 61253f1 commit b517fda
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
22 changes: 22 additions & 0 deletions decode_hooks.go
Original file line number Diff line number Diff line change
@@ -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
}
}
39 changes: 39 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit b517fda

Please sign in to comment.