Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
prevent panic in TextUnmarshallerHookFunc
Browse files Browse the repository at this point in the history
if reflect.Kind is reflect.String, it doesn't necessary means it's
`string` type. It can be string-based type
  • Loading branch information
prochac committed Apr 18, 2023
1 parent bf980b3 commit 63cde0d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion decode_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,11 @@ func TextUnmarshallerHookFunc() DecodeHookFuncType {
if !ok {
return data, nil
}
if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil {
str, ok := data.(string)
if !ok {
str = reflect.Indirect(reflect.ValueOf(&data)).Elem().String()
}
if err := unmarshaller.UnmarshalText([]byte(str)); err != nil {
return nil, err
}
return result, nil
Expand Down
6 changes: 5 additions & 1 deletion decode_hooks_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mapstructure

import (
"encoding/json"
"errors"
"math/big"
"net"
Expand Down Expand Up @@ -542,6 +543,8 @@ func TestStructToMapHookFuncTabled(t *testing.T) {
}

func TestTextUnmarshallerHookFunc(t *testing.T) {
type MyString string

cases := []struct {
f, t reflect.Value
result interface{}
Expand All @@ -550,8 +553,9 @@ func TestTextUnmarshallerHookFunc(t *testing.T) {
{reflect.ValueOf("42"), reflect.ValueOf(big.Int{}), big.NewInt(42), false},
{reflect.ValueOf("invalid"), reflect.ValueOf(big.Int{}), nil, true},
{reflect.ValueOf("5"), reflect.ValueOf("5"), "5", false},
{reflect.ValueOf(json.Number("42")), reflect.ValueOf(big.Int{}), big.NewInt(42), false},
{reflect.ValueOf(MyString("42")), reflect.ValueOf(big.Int{}), big.NewInt(42), false},
}

for i, tc := range cases {
f := TextUnmarshallerHookFunc()
actual, err := DecodeHookExec(f, tc.f, tc.t)
Expand Down

0 comments on commit 63cde0d

Please sign in to comment.