feat: support uuid.UUID in mapping (#2537)

This commit is contained in:
Kevin Wan
2022-10-20 20:11:19 +08:00
committed by GitHub
parent de5c59aad3
commit f9beab1095
2 changed files with 54 additions and 2 deletions

View File

@@ -1,6 +1,7 @@
package mapping
import (
"encoding"
"encoding/json"
"errors"
"fmt"
@@ -318,6 +319,28 @@ func (u *Unmarshaler) processFieldStructWithMap(field reflect.StructField, value
return nil
}
func (u *Unmarshaler) processFieldTextUnmarshaler(field reflect.StructField, value reflect.Value,
mapValue interface{}) (bool, error) {
var tval encoding.TextUnmarshaler
var ok bool
if field.Type.Kind() == reflect.Ptr {
tval, ok = value.Interface().(encoding.TextUnmarshaler)
} else {
tval, ok = value.Addr().Interface().(encoding.TextUnmarshaler)
}
if ok {
switch mv := mapValue.(type) {
case string:
return true, tval.UnmarshalText([]byte(mv))
case []byte:
return true, tval.UnmarshalText(mv)
}
}
return false, nil
}
func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect.Value,
m Valuer, fullName string) error {
key, opts, err := u.parseOptionsWithContext(field, m, fullName)
@@ -348,8 +371,16 @@ func (u *Unmarshaler) processNamedFieldWithValue(field reflect.StructField, valu
return fmt.Errorf("field %s mustn't be nil", key)
}
if !value.CanSet() {
return fmt.Errorf("field %s is not settable", key)
}
maybeNewValue(field, value)
if yes, err := u.processFieldTextUnmarshaler(field, value, mapValue); yes {
return err
}
fieldKind := Deref(field.Type).Kind()
switch fieldKind {
case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: