Skip to content

Commit

Permalink
Merge pull request #52 from mahadzaryab1/reflect-value-hook
Browse files Browse the repository at this point in the history
[enhancement] Add check for `reflect.Value` in `ComposeDecodeHookFunc`
  • Loading branch information
sagikazarmark authored Nov 18, 2024
2 parents 0b972d9 + 5d61bd5 commit 2cb620d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
6 changes: 5 additions & 1 deletion decode_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,11 @@ func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
if err != nil {
return nil, err
}
newFrom = reflect.ValueOf(data)
if v, ok := data.(reflect.Value); ok {
newFrom = v
} else {
newFrom = reflect.ValueOf(data)
}
}

return data, nil
Expand Down
30 changes: 30 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,36 @@ func TestComposeDecodeHookFunc_safe_nofuncs(t *testing.T) {
}
}

func TestComposeDecodeHookFunc_ReflectValueHook(t *testing.T) {
reflectValueHook := func(
f reflect.Kind,
t reflect.Kind,
data interface{},
) (interface{}, error) {
new := data.(string) + "foo"
return reflect.ValueOf(new), nil
}

stringHook := func(
f reflect.Kind,
t reflect.Kind,
data interface{},
) (interface{}, error) {
return data.(string) + "bar", nil
}

f := ComposeDecodeHookFunc(reflectValueHook, stringHook)

result, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if result.(string) != "foobar" {
t.Fatalf("bad: %#v", result)
}
}

func TestStringToSliceHookFunc(t *testing.T) {
f := StringToSliceHookFunc(",")

Expand Down

0 comments on commit 2cb620d

Please sign in to comment.