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

Commit

Permalink
Merge pull request #222 from sqills/feature/text-unmarshaller-hook
Browse files Browse the repository at this point in the history
Ability to use encoding.TextUnmarshaler
  • Loading branch information
mitchellh authored Jan 4, 2021
2 parents 2fb8a82 + 2da917e commit 1b4332d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
24 changes: 24 additions & 0 deletions decode_hooks.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mapstructure

import (
"encoding"
"errors"
"fmt"
"net"
Expand Down Expand Up @@ -230,3 +231,26 @@ func RecursiveStructToMapHookFunc() DecodeHookFunc {
return f.Interface(), nil
}
}

// TextUnmarshallerHookFunc returns a DecodeHookFunc that applies
// strings to the UnmarshalText function, when the target type
// implements the encoding.TextUnmarshaler interface
func TextUnmarshallerHookFunc() DecodeHookFuncType {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
result := reflect.New(t).Interface()
unmarshaller, ok := result.(encoding.TextUnmarshaler)
if !ok {
return data, nil
}
if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil {
return nil, err
}
return result, nil
}
}
26 changes: 26 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package mapstructure

import (
"errors"
"math/big"
"net"
"reflect"
"testing"
Expand Down Expand Up @@ -419,3 +420,28 @@ func TestStructToMapHookFuncTabled(t *testing.T) {

}
}

func TestTextUnmarshallerHookFunc(t *testing.T) {
cases := []struct {
f, t reflect.Value
result interface{}
err bool
}{
{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},
}

for i, tc := range cases {
f := TextUnmarshallerHookFunc()
actual, err := DecodeHookExec(f, tc.f, tc.t)
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 1b4332d

Please sign in to comment.