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

prevent panic in TextUnmarshallerHookFunc #328

Merged
merged 1 commit into from
Dec 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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