123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737 |
- package mapping
- import (
- "encoding/json"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "sync"
- "sync/atomic"
- "time"
- "github.com/tal-tech/go-zero/core/jsonx"
- "github.com/tal-tech/go-zero/core/lang"
- "github.com/tal-tech/go-zero/core/stringx"
- )
- const (
- defaultKeyName = "key"
- delimiter = '.'
- )
- var (
- errTypeMismatch = errors.New("type mismatch")
- errValueNotSettable = errors.New("value is not settable")
- keyUnmarshaler = NewUnmarshaler(defaultKeyName)
- cacheKeys atomic.Value
- cacheKeysLock sync.Mutex
- durationType = reflect.TypeOf(time.Duration(0))
- emptyMap = map[string]interface{}{}
- emptyValue = reflect.ValueOf(lang.Placeholder)
- )
- type (
- Unmarshaler struct {
- key string
- opts unmarshalOptions
- }
- unmarshalOptions struct {
- fromString bool
- }
- keyCache map[string][]string
- UnmarshalOption func(*unmarshalOptions)
- )
- func init() {
- cacheKeys.Store(make(keyCache))
- }
- func NewUnmarshaler(key string, opts ...UnmarshalOption) *Unmarshaler {
- unmarshaler := Unmarshaler{
- key: key,
- }
- for _, opt := range opts {
- opt(&unmarshaler.opts)
- }
- return &unmarshaler
- }
- func UnmarshalKey(m map[string]interface{}, v interface{}) error {
- return keyUnmarshaler.Unmarshal(m, v)
- }
- func (u *Unmarshaler) Unmarshal(m map[string]interface{}, v interface{}) error {
- return u.UnmarshalValuer(MapValuer(m), v)
- }
- func (u *Unmarshaler) UnmarshalValuer(m Valuer, v interface{}) error {
- return u.unmarshalWithFullName(m, v, "")
- }
- func (u *Unmarshaler) unmarshalWithFullName(m Valuer, v interface{}, fullName string) error {
- rv := reflect.ValueOf(v)
- if err := ValidatePtr(&rv); err != nil {
- return err
- }
- rte := reflect.TypeOf(v).Elem()
- rve := rv.Elem()
- numFields := rte.NumField()
- for i := 0; i < numFields; i++ {
- field := rte.Field(i)
- if usingDifferentKeys(u.key, field) {
- continue
- }
- if err := u.processField(field, rve.Field(i), m, fullName); err != nil {
- return err
- }
- }
- return nil
- }
- func (u *Unmarshaler) processAnonymousField(field reflect.StructField, value reflect.Value,
- m Valuer, fullName string) error {
- key, options, err := u.parseOptionsWithContext(field, m, fullName)
- if err != nil {
- return err
- }
- if _, hasValue := getValue(m, key); hasValue {
- return fmt.Errorf("fields of %s can't be wrapped inside, because it's anonymous", key)
- }
- if options.optional() {
- return u.processAnonymousFieldOptional(field, value, key, m, fullName)
- } else {
- return u.processAnonymousFieldRequired(field, value, m, fullName)
- }
- }
- func (u *Unmarshaler) processAnonymousFieldOptional(field reflect.StructField, value reflect.Value,
- key string, m Valuer, fullName string) error {
- var filled bool
- var required int
- var requiredFilled int
- var indirectValue reflect.Value
- fieldType := Deref(field.Type)
- for i := 0; i < fieldType.NumField(); i++ {
- subField := fieldType.Field(i)
- fieldKey, fieldOpts, err := u.parseOptionsWithContext(subField, m, fullName)
- if err != nil {
- return err
- }
- _, hasValue := getValue(m, fieldKey)
- if hasValue {
- if !filled {
- filled = true
- maybeNewValue(field, value)
- indirectValue = reflect.Indirect(value)
- }
- if err = u.processField(subField, indirectValue.Field(i), m, fullName); err != nil {
- return err
- }
- }
- if !fieldOpts.optional() {
- required++
- if hasValue {
- requiredFilled++
- }
- }
- }
- if filled && required != requiredFilled {
- return fmt.Errorf("%s is not fully set", key)
- }
- return nil
- }
- func (u *Unmarshaler) processAnonymousFieldRequired(field reflect.StructField, value reflect.Value,
- m Valuer, fullName string) error {
- maybeNewValue(field, value)
- fieldType := Deref(field.Type)
- indirectValue := reflect.Indirect(value)
- for i := 0; i < fieldType.NumField(); i++ {
- if err := u.processField(fieldType.Field(i), indirectValue.Field(i), m, fullName); err != nil {
- return err
- }
- }
- return nil
- }
- func (u *Unmarshaler) processField(field reflect.StructField, value reflect.Value, m Valuer,
- fullName string) error {
- if usingDifferentKeys(u.key, field) {
- return nil
- }
- if field.Anonymous {
- return u.processAnonymousField(field, value, m, fullName)
- } else {
- return u.processNamedField(field, value, m, fullName)
- }
- }
- func (u *Unmarshaler) processFieldNotFromString(field reflect.StructField, value reflect.Value,
- mapValue interface{}, opts *fieldOptionsWithContext, fullName string) error {
- fieldType := field.Type
- derefedFieldType := Deref(fieldType)
- typeKind := derefedFieldType.Kind()
- valueKind := reflect.TypeOf(mapValue).Kind()
- switch {
- case valueKind == reflect.Map && typeKind == reflect.Struct:
- return u.processFieldStruct(field, value, mapValue, fullName)
- case valueKind == reflect.String && typeKind == reflect.Slice:
- return u.fillSliceFromString(fieldType, value, mapValue, fullName)
- case valueKind == reflect.String && derefedFieldType == durationType:
- return fillDurationValue(fieldType.Kind(), value, mapValue.(string))
- default:
- return u.processFieldPrimitive(field, value, mapValue, opts, fullName)
- }
- }
- func (u *Unmarshaler) processFieldPrimitive(field reflect.StructField, value reflect.Value,
- mapValue interface{}, opts *fieldOptionsWithContext, fullName string) error {
- fieldType := field.Type
- typeKind := Deref(fieldType).Kind()
- valueKind := reflect.TypeOf(mapValue).Kind()
- switch {
- case typeKind == reflect.Slice && valueKind == reflect.Slice:
- return u.fillSlice(fieldType, value, mapValue)
- case typeKind == reflect.Map && valueKind == reflect.Map:
- return u.fillMap(field, value, mapValue)
- default:
- switch v := mapValue.(type) {
- case json.Number:
- return u.processFieldPrimitiveWithJsonNumber(field, value, v, opts, fullName)
- default:
- if typeKind == valueKind {
- if err := validateValueInOptions(opts.options(), mapValue); err != nil {
- return err
- }
- return fillWithSameType(field, value, mapValue, opts)
- }
- }
- }
- return newTypeMismatchError(fullName)
- }
- func (u *Unmarshaler) processFieldPrimitiveWithJsonNumber(field reflect.StructField, value reflect.Value,
- v json.Number, opts *fieldOptionsWithContext, fullName string) error {
- fieldType := field.Type
- fieldKind := fieldType.Kind()
- typeKind := Deref(fieldType).Kind()
- if err := validateJsonNumberRange(v, opts); err != nil {
- return err
- }
- if fieldKind == reflect.Ptr {
- value = value.Elem()
- }
- switch typeKind {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- iValue, err := v.Int64()
- if err != nil {
- return err
- }
- value.SetInt(iValue)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- iValue, err := v.Int64()
- if err != nil {
- return err
- }
- value.SetUint(uint64(iValue))
- case reflect.Float32, reflect.Float64:
- fValue, err := v.Float64()
- if err != nil {
- return err
- }
- value.SetFloat(fValue)
- default:
- return newTypeMismatchError(fullName)
- }
- return nil
- }
- func (u *Unmarshaler) processFieldStruct(field reflect.StructField, value reflect.Value,
- mapValue interface{}, fullName string) error {
- convertedValue, ok := mapValue.(map[string]interface{})
- if !ok {
- valueKind := reflect.TypeOf(mapValue).Kind()
- return fmt.Errorf("error: field: %s, expect map[string]interface{}, actual %v", fullName, valueKind)
- }
- return u.processFieldStructWithMap(field, value, MapValuer(convertedValue), fullName)
- }
- func (u *Unmarshaler) processFieldStructWithMap(field reflect.StructField, value reflect.Value,
- m Valuer, fullName string) error {
- if field.Type.Kind() == reflect.Ptr {
- baseType := Deref(field.Type)
- target := reflect.New(baseType).Elem()
- if err := u.unmarshalWithFullName(m, target.Addr().Interface(), fullName); err != nil {
- return err
- }
- value.Set(target.Addr())
- } else if err := u.unmarshalWithFullName(m, value.Addr().Interface(), fullName); err != nil {
- return err
- }
- return nil
- }
- func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect.Value,
- m Valuer, fullName string) error {
- key, opts, err := u.parseOptionsWithContext(field, m, fullName)
- if err != nil {
- return err
- }
- fullName = join(fullName, key)
- mapValue, hasValue := getValue(m, key)
- if hasValue {
- return u.processNamedFieldWithValue(field, value, mapValue, key, opts, fullName)
- } else {
- return u.processNamedFieldWithoutValue(field, value, opts, fullName)
- }
- }
- func (u *Unmarshaler) processNamedFieldWithValue(field reflect.StructField, value reflect.Value,
- mapValue interface{}, key string, opts *fieldOptionsWithContext, fullName string) error {
- if mapValue == nil {
- if opts.optional() {
- return nil
- } else {
- return fmt.Errorf("field %s mustn't be nil", key)
- }
- }
- maybeNewValue(field, value)
- fieldKind := Deref(field.Type).Kind()
- switch fieldKind {
- case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
- return u.processFieldNotFromString(field, value, mapValue, opts, fullName)
- default:
- if u.opts.fromString || opts.fromString() {
- valueKind := reflect.TypeOf(mapValue).Kind()
- if valueKind != reflect.String {
- return fmt.Errorf("error: the value in map is not string, but %s", valueKind)
- }
- options := opts.options()
- if len(options) > 0 {
- if !stringx.Contains(options, mapValue.(string)) {
- return fmt.Errorf(`error: value "%s" for field "%s" is not defined in options "%v"`,
- mapValue, key, options)
- }
- }
- return fillPrimitive(field.Type, value, mapValue, opts, fullName)
- }
- return u.processFieldNotFromString(field, value, mapValue, opts, fullName)
- }
- }
- func (u *Unmarshaler) processNamedFieldWithoutValue(field reflect.StructField, value reflect.Value,
- opts *fieldOptionsWithContext, fullName string) error {
- derefedType := Deref(field.Type)
- fieldKind := derefedType.Kind()
- if defaultValue, ok := opts.getDefault(); ok {
- if field.Type.Kind() == reflect.Ptr {
- maybeNewValue(field, value)
- value = value.Elem()
- }
- if derefedType == durationType {
- return fillDurationValue(fieldKind, value, defaultValue)
- }
- return setValue(fieldKind, value, defaultValue)
- }
- switch fieldKind {
- case reflect.Array, reflect.Map, reflect.Slice:
- if !opts.optional() {
- return u.processFieldNotFromString(field, value, emptyMap, opts, fullName)
- }
- case reflect.Struct:
- if !opts.optional() {
- required, err := structValueRequired(u.key, derefedType)
- if err != nil {
- return err
- }
- if required {
- return fmt.Errorf("%q is not set", fullName)
- }
- return u.processFieldNotFromString(field, value, emptyMap, opts, fullName)
- }
- default:
- if !opts.optional() {
- return newInitError(fullName)
- }
- }
- return nil
- }
- func (u *Unmarshaler) fillMap(field reflect.StructField, value reflect.Value, mapValue interface{}) error {
- if !value.CanSet() {
- return errValueNotSettable
- }
- fieldKeyType := field.Type.Key()
- fieldElemType := field.Type.Elem()
- targetValue, err := u.generateMap(fieldKeyType, fieldElemType, mapValue)
- if err != nil {
- return err
- }
- value.Set(targetValue)
- return nil
- }
- func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
- if !value.CanSet() {
- return errValueNotSettable
- }
- baseType := fieldType.Elem()
- baseKind := baseType.Kind()
- dereffedBaseType := Deref(baseType)
- dereffedBaseKind := dereffedBaseType.Kind()
- refValue := reflect.ValueOf(mapValue)
- conv := reflect.MakeSlice(reflect.SliceOf(baseType), refValue.Len(), refValue.Cap())
- var valid bool
- for i := 0; i < refValue.Len(); i++ {
- ithValue := refValue.Index(i).Interface()
- if ithValue == nil {
- continue
- }
- valid = true
- switch dereffedBaseKind {
- case reflect.Struct:
- target := reflect.New(dereffedBaseType)
- if err := u.Unmarshal(ithValue.(map[string]interface{}), target.Interface()); err != nil {
- return err
- }
- if baseKind == reflect.Ptr {
- conv.Index(i).Set(target)
- } else {
- conv.Index(i).Set(target.Elem())
- }
- default:
- if err := u.fillSliceValue(conv, i, dereffedBaseKind, ithValue); err != nil {
- return err
- }
- }
- }
- if valid {
- value.Set(conv)
- }
- return nil
- }
- func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value,
- mapValue interface{}, fullName string) error {
- var slice []interface{}
- if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil {
- return err
- }
- baseFieldType := Deref(fieldType.Elem())
- baseFieldKind := baseFieldType.Kind()
- conv := reflect.MakeSlice(reflect.SliceOf(baseFieldType), len(slice), cap(slice))
- for i := 0; i < len(slice); i++ {
- if err := u.fillSliceValue(conv, i, baseFieldKind, slice[i]); err != nil {
- return err
- }
- }
- value.Set(conv)
- return nil
- }
- func (u *Unmarshaler) fillSliceValue(slice reflect.Value, index int, baseKind reflect.Kind, value interface{}) error {
- switch v := value.(type) {
- case json.Number:
- return setValue(baseKind, slice.Index(index), v.String())
- default:
- // don't need to consider the difference between int, int8, int16, int32, int64,
- // uint, uint8, uint16, uint32, uint64, because they're handled as json.Number.
- if slice.Index(index).Kind() != reflect.TypeOf(value).Kind() {
- return errTypeMismatch
- }
- slice.Index(index).Set(reflect.ValueOf(value))
- return nil
- }
- }
- func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue interface{}) (reflect.Value, error) {
- mapType := reflect.MapOf(keyType, elemType)
- valueType := reflect.TypeOf(mapValue)
- if mapType == valueType {
- return reflect.ValueOf(mapValue), nil
- }
- refValue := reflect.ValueOf(mapValue)
- targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
- fieldElemKind := elemType.Kind()
- dereffedElemType := Deref(elemType)
- dereffedElemKind := dereffedElemType.Kind()
- for _, key := range refValue.MapKeys() {
- keythValue := refValue.MapIndex(key)
- keythData := keythValue.Interface()
- switch dereffedElemKind {
- case reflect.Slice:
- target := reflect.New(dereffedElemType)
- if err := u.fillSlice(elemType, target.Elem(), keythData); err != nil {
- return emptyValue, err
- }
- targetValue.SetMapIndex(key, target.Elem())
- case reflect.Struct:
- keythMap, ok := keythData.(map[string]interface{})
- if !ok {
- return emptyValue, errTypeMismatch
- }
- target := reflect.New(dereffedElemType)
- if err := u.Unmarshal(keythMap, target.Interface()); err != nil {
- return emptyValue, err
- }
- if fieldElemKind == reflect.Ptr {
- targetValue.SetMapIndex(key, target)
- } else {
- targetValue.SetMapIndex(key, target.Elem())
- }
- case reflect.Map:
- keythMap, ok := keythData.(map[string]interface{})
- if !ok {
- return emptyValue, errTypeMismatch
- }
- innerValue, err := u.generateMap(elemType.Key(), elemType.Elem(), keythMap)
- if err != nil {
- return emptyValue, err
- }
- targetValue.SetMapIndex(key, innerValue)
- default:
- switch v := keythData.(type) {
- case string:
- targetValue.SetMapIndex(key, reflect.ValueOf(v))
- case json.Number:
- target := reflect.New(dereffedElemType)
- if err := setValue(dereffedElemKind, target.Elem(), v.String()); err != nil {
- return emptyValue, err
- }
- targetValue.SetMapIndex(key, target.Elem())
- default:
- targetValue.SetMapIndex(key, keythValue)
- }
- }
- }
- return targetValue, nil
- }
- func (u *Unmarshaler) parseOptionsWithContext(field reflect.StructField, m Valuer, fullName string) (
- string, *fieldOptionsWithContext, error) {
- key, options, err := parseKeyAndOptions(u.key, field)
- if err != nil {
- return "", nil, err
- } else if options == nil {
- return key, nil, nil
- }
- optsWithContext, err := options.toOptionsWithContext(key, m, fullName)
- if err != nil {
- return "", nil, err
- }
- return key, optsWithContext, nil
- }
- func WithStringValues() UnmarshalOption {
- return func(opt *unmarshalOptions) {
- opt.fromString = true
- }
- }
- func fillDurationValue(fieldKind reflect.Kind, value reflect.Value, dur string) error {
- d, err := time.ParseDuration(dur)
- if err != nil {
- return err
- }
- if fieldKind == reflect.Ptr {
- value.Elem().Set(reflect.ValueOf(d))
- } else {
- value.Set(reflect.ValueOf(d))
- }
- return nil
- }
- func fillPrimitive(fieldType reflect.Type, value reflect.Value, mapValue interface{},
- opts *fieldOptionsWithContext, fullName string) error {
- if !value.CanSet() {
- return errValueNotSettable
- }
- baseType := Deref(fieldType)
- if fieldType.Kind() == reflect.Ptr {
- target := reflect.New(baseType).Elem()
- switch mapValue.(type) {
- case string, json.Number:
- value.Set(target.Addr())
- value = target
- }
- }
- switch v := mapValue.(type) {
- case string:
- return validateAndSetValue(baseType.Kind(), value, v, opts)
- case json.Number:
- if err := validateJsonNumberRange(v, opts); err != nil {
- return err
- }
- return setValue(baseType.Kind(), value, v.String())
- default:
- return newTypeMismatchError(fullName)
- }
- }
- func fillWithSameType(field reflect.StructField, value reflect.Value, mapValue interface{},
- opts *fieldOptionsWithContext) error {
- if !value.CanSet() {
- return errValueNotSettable
- }
- if err := validateValueRange(mapValue, opts); err != nil {
- return err
- }
- if field.Type.Kind() == reflect.Ptr {
- baseType := Deref(field.Type)
- target := reflect.New(baseType).Elem()
- target.Set(reflect.ValueOf(mapValue))
- value.Set(target.Addr())
- } else {
- value.Set(reflect.ValueOf(mapValue))
- }
- return nil
- }
- // getValue gets the value for the specific key, the key can be in the format of parentKey.childKey
- func getValue(m Valuer, key string) (interface{}, bool) {
- keys := readKeys(key)
- return getValueWithChainedKeys(m, keys)
- }
- func getValueWithChainedKeys(m Valuer, keys []string) (interface{}, bool) {
- if len(keys) == 1 {
- v, ok := m.Value(keys[0])
- return v, ok
- } else if len(keys) > 1 {
- if v, ok := m.Value(keys[0]); ok {
- if nextm, ok := v.(map[string]interface{}); ok {
- return getValueWithChainedKeys(MapValuer(nextm), keys[1:])
- }
- }
- }
- return nil, false
- }
- func insertKeys(key string, cache []string) {
- cacheKeysLock.Lock()
- defer cacheKeysLock.Unlock()
- keys := cacheKeys.Load().(keyCache)
- // copy the contents into the new map, to guarantee the old map is immutable
- newKeys := make(keyCache)
- for k, v := range keys {
- newKeys[k] = v
- }
- newKeys[key] = cache
- cacheKeys.Store(newKeys)
- }
- func join(elem ...string) string {
- var builder strings.Builder
- var fillSep bool
- for _, e := range elem {
- if len(e) == 0 {
- continue
- }
- if fillSep {
- builder.WriteByte(delimiter)
- } else {
- fillSep = true
- }
- builder.WriteString(e)
- }
- return builder.String()
- }
- func newInitError(name string) error {
- return fmt.Errorf("field %s is not set", name)
- }
- func newTypeMismatchError(name string) error {
- return fmt.Errorf("error: type mismatch for field %s", name)
- }
- func readKeys(key string) []string {
- cache := cacheKeys.Load().(keyCache)
- if keys, ok := cache[key]; ok {
- return keys
- }
- keys := strings.FieldsFunc(key, func(c rune) bool {
- return c == delimiter
- })
- insertKeys(key, keys)
- return keys
- }
|