unmarshaler.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. package mapping
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "git.i2edu.net/i2/go-zero/core/jsonx"
  12. "git.i2edu.net/i2/go-zero/core/lang"
  13. "git.i2edu.net/i2/go-zero/core/stringx"
  14. )
  15. const (
  16. defaultKeyName = "key"
  17. delimiter = '.'
  18. )
  19. var (
  20. errTypeMismatch = errors.New("type mismatch")
  21. errValueNotSettable = errors.New("value is not settable")
  22. errValueNotStruct = errors.New("value type is not struct")
  23. keyUnmarshaler = NewUnmarshaler(defaultKeyName)
  24. cacheKeys atomic.Value
  25. cacheKeysLock sync.Mutex
  26. durationType = reflect.TypeOf(time.Duration(0))
  27. emptyMap = map[string]interface{}{}
  28. emptyValue = reflect.ValueOf(lang.Placeholder)
  29. )
  30. type (
  31. // A Unmarshaler is used to unmarshal with given tag key.
  32. Unmarshaler struct {
  33. key string
  34. opts unmarshalOptions
  35. }
  36. // UnmarshalOption defines the method to customize a Unmarshaler.
  37. UnmarshalOption func(*unmarshalOptions)
  38. unmarshalOptions struct {
  39. fromString bool
  40. }
  41. keyCache map[string][]string
  42. )
  43. func init() {
  44. cacheKeys.Store(make(keyCache))
  45. }
  46. // NewUnmarshaler returns a Unmarshaler.
  47. func NewUnmarshaler(key string, opts ...UnmarshalOption) *Unmarshaler {
  48. unmarshaler := Unmarshaler{
  49. key: key,
  50. }
  51. for _, opt := range opts {
  52. opt(&unmarshaler.opts)
  53. }
  54. return &unmarshaler
  55. }
  56. // UnmarshalKey unmarshals m into v with tag key.
  57. func UnmarshalKey(m map[string]interface{}, v interface{}) error {
  58. return keyUnmarshaler.Unmarshal(m, v)
  59. }
  60. // Unmarshal unmarshals m into v.
  61. func (u *Unmarshaler) Unmarshal(m map[string]interface{}, v interface{}) error {
  62. return u.UnmarshalValuer(MapValuer(m), v)
  63. }
  64. // UnmarshalValuer unmarshals m into v.
  65. func (u *Unmarshaler) UnmarshalValuer(m Valuer, v interface{}) error {
  66. return u.unmarshalWithFullName(m, v, "")
  67. }
  68. func (u *Unmarshaler) unmarshalWithFullName(m Valuer, v interface{}, fullName string) error {
  69. rv := reflect.ValueOf(v)
  70. if err := ValidatePtr(&rv); err != nil {
  71. return err
  72. }
  73. rte := reflect.TypeOf(v).Elem()
  74. if rte.Kind() != reflect.Struct {
  75. return errValueNotStruct
  76. }
  77. rve := rv.Elem()
  78. numFields := rte.NumField()
  79. for i := 0; i < numFields; i++ {
  80. field := rte.Field(i)
  81. if usingDifferentKeys(u.key, field) {
  82. continue
  83. }
  84. if err := u.processField(field, rve.Field(i), m, fullName); err != nil {
  85. return err
  86. }
  87. }
  88. return nil
  89. }
  90. func (u *Unmarshaler) processAnonymousField(field reflect.StructField, value reflect.Value,
  91. m Valuer, fullName string) error {
  92. key, options, err := u.parseOptionsWithContext(field, m, fullName)
  93. if err != nil {
  94. return err
  95. }
  96. if _, hasValue := getValue(m, key); hasValue {
  97. return fmt.Errorf("fields of %s can't be wrapped inside, because it's anonymous", key)
  98. }
  99. if options.optional() {
  100. return u.processAnonymousFieldOptional(field, value, key, m, fullName)
  101. }
  102. return u.processAnonymousFieldRequired(field, value, m, fullName)
  103. }
  104. func (u *Unmarshaler) processAnonymousFieldOptional(field reflect.StructField, value reflect.Value,
  105. key string, m Valuer, fullName string) error {
  106. var filled bool
  107. var required int
  108. var requiredFilled int
  109. var indirectValue reflect.Value
  110. fieldType := Deref(field.Type)
  111. for i := 0; i < fieldType.NumField(); i++ {
  112. subField := fieldType.Field(i)
  113. fieldKey, fieldOpts, err := u.parseOptionsWithContext(subField, m, fullName)
  114. if err != nil {
  115. return err
  116. }
  117. _, hasValue := getValue(m, fieldKey)
  118. if hasValue {
  119. if !filled {
  120. filled = true
  121. maybeNewValue(field, value)
  122. indirectValue = reflect.Indirect(value)
  123. }
  124. if err = u.processField(subField, indirectValue.Field(i), m, fullName); err != nil {
  125. return err
  126. }
  127. }
  128. if !fieldOpts.optional() {
  129. required++
  130. if hasValue {
  131. requiredFilled++
  132. }
  133. }
  134. }
  135. if filled && required != requiredFilled {
  136. return fmt.Errorf("%s is not fully set", key)
  137. }
  138. return nil
  139. }
  140. func (u *Unmarshaler) processAnonymousFieldRequired(field reflect.StructField, value reflect.Value,
  141. m Valuer, fullName string) error {
  142. maybeNewValue(field, value)
  143. fieldType := Deref(field.Type)
  144. indirectValue := reflect.Indirect(value)
  145. for i := 0; i < fieldType.NumField(); i++ {
  146. if err := u.processField(fieldType.Field(i), indirectValue.Field(i), m, fullName); err != nil {
  147. return err
  148. }
  149. }
  150. return nil
  151. }
  152. func (u *Unmarshaler) processField(field reflect.StructField, value reflect.Value, m Valuer,
  153. fullName string) error {
  154. if usingDifferentKeys(u.key, field) {
  155. return nil
  156. }
  157. if field.Anonymous {
  158. return u.processAnonymousField(field, value, m, fullName)
  159. }
  160. return u.processNamedField(field, value, m, fullName)
  161. }
  162. func (u *Unmarshaler) processFieldNotFromString(field reflect.StructField, value reflect.Value,
  163. mapValue interface{}, opts *fieldOptionsWithContext, fullName string) error {
  164. fieldType := field.Type
  165. derefedFieldType := Deref(fieldType)
  166. typeKind := derefedFieldType.Kind()
  167. valueKind := reflect.TypeOf(mapValue).Kind()
  168. switch {
  169. case valueKind == reflect.Map && typeKind == reflect.Struct:
  170. return u.processFieldStruct(field, value, mapValue, fullName)
  171. case valueKind == reflect.String && typeKind == reflect.Slice:
  172. return u.fillSliceFromString(fieldType, value, mapValue)
  173. case valueKind == reflect.String && derefedFieldType == durationType:
  174. return fillDurationValue(fieldType.Kind(), value, mapValue.(string))
  175. default:
  176. return u.processFieldPrimitive(field, value, mapValue, opts, fullName)
  177. }
  178. }
  179. func (u *Unmarshaler) processFieldPrimitive(field reflect.StructField, value reflect.Value,
  180. mapValue interface{}, opts *fieldOptionsWithContext, fullName string) error {
  181. fieldType := field.Type
  182. typeKind := Deref(fieldType).Kind()
  183. valueKind := reflect.TypeOf(mapValue).Kind()
  184. switch {
  185. case typeKind == reflect.Slice && valueKind == reflect.Slice:
  186. return u.fillSlice(fieldType, value, mapValue)
  187. case typeKind == reflect.Map && valueKind == reflect.Map:
  188. return u.fillMap(field, value, mapValue)
  189. default:
  190. switch v := mapValue.(type) {
  191. case json.Number:
  192. return u.processFieldPrimitiveWithJsonNumber(field, value, v, opts, fullName)
  193. default:
  194. if typeKind == valueKind {
  195. if err := validateValueInOptions(opts.options(), mapValue); err != nil {
  196. return err
  197. }
  198. return fillWithSameType(field, value, mapValue, opts)
  199. }
  200. }
  201. }
  202. return newTypeMismatchError(fullName)
  203. }
  204. func (u *Unmarshaler) processFieldPrimitiveWithJsonNumber(field reflect.StructField, value reflect.Value,
  205. v json.Number, opts *fieldOptionsWithContext, fullName string) error {
  206. fieldType := field.Type
  207. fieldKind := fieldType.Kind()
  208. typeKind := Deref(fieldType).Kind()
  209. if err := validateJsonNumberRange(v, opts); err != nil {
  210. return err
  211. }
  212. if fieldKind == reflect.Ptr {
  213. value = value.Elem()
  214. }
  215. switch typeKind {
  216. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  217. iValue, err := v.Int64()
  218. if err != nil {
  219. return err
  220. }
  221. value.SetInt(iValue)
  222. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  223. iValue, err := v.Int64()
  224. if err != nil {
  225. return err
  226. }
  227. value.SetUint(uint64(iValue))
  228. case reflect.Float32, reflect.Float64:
  229. fValue, err := v.Float64()
  230. if err != nil {
  231. return err
  232. }
  233. value.SetFloat(fValue)
  234. default:
  235. return newTypeMismatchError(fullName)
  236. }
  237. return nil
  238. }
  239. func (u *Unmarshaler) processFieldStruct(field reflect.StructField, value reflect.Value,
  240. mapValue interface{}, fullName string) error {
  241. convertedValue, ok := mapValue.(map[string]interface{})
  242. if !ok {
  243. valueKind := reflect.TypeOf(mapValue).Kind()
  244. return fmt.Errorf("error: field: %s, expect map[string]interface{}, actual %v", fullName, valueKind)
  245. }
  246. return u.processFieldStructWithMap(field, value, MapValuer(convertedValue), fullName)
  247. }
  248. func (u *Unmarshaler) processFieldStructWithMap(field reflect.StructField, value reflect.Value,
  249. m Valuer, fullName string) error {
  250. if field.Type.Kind() == reflect.Ptr {
  251. baseType := Deref(field.Type)
  252. target := reflect.New(baseType).Elem()
  253. if err := u.unmarshalWithFullName(m, target.Addr().Interface(), fullName); err != nil {
  254. return err
  255. }
  256. value.Set(target.Addr())
  257. } else if err := u.unmarshalWithFullName(m, value.Addr().Interface(), fullName); err != nil {
  258. return err
  259. }
  260. return nil
  261. }
  262. func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect.Value,
  263. m Valuer, fullName string) error {
  264. key, opts, err := u.parseOptionsWithContext(field, m, fullName)
  265. if err != nil {
  266. return err
  267. }
  268. fullName = join(fullName, key)
  269. mapValue, hasValue := getValue(m, key)
  270. if hasValue {
  271. return u.processNamedFieldWithValue(field, value, mapValue, key, opts, fullName)
  272. }
  273. return u.processNamedFieldWithoutValue(field, value, opts, fullName)
  274. }
  275. func (u *Unmarshaler) processNamedFieldWithValue(field reflect.StructField, value reflect.Value,
  276. mapValue interface{}, key string, opts *fieldOptionsWithContext, fullName string) error {
  277. if mapValue == nil {
  278. if opts.optional() {
  279. return nil
  280. }
  281. return fmt.Errorf("field %s mustn't be nil", key)
  282. }
  283. maybeNewValue(field, value)
  284. fieldKind := Deref(field.Type).Kind()
  285. switch fieldKind {
  286. case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
  287. return u.processFieldNotFromString(field, value, mapValue, opts, fullName)
  288. default:
  289. if u.opts.fromString || opts.fromString() {
  290. valueKind := reflect.TypeOf(mapValue).Kind()
  291. if valueKind != reflect.String {
  292. return fmt.Errorf("error: the value in map is not string, but %s", valueKind)
  293. }
  294. options := opts.options()
  295. if len(options) > 0 {
  296. if !stringx.Contains(options, mapValue.(string)) {
  297. return fmt.Errorf(`error: value "%s" for field "%s" is not defined in options "%v"`,
  298. mapValue, key, options)
  299. }
  300. }
  301. return fillPrimitive(field.Type, value, mapValue, opts, fullName)
  302. }
  303. return u.processFieldNotFromString(field, value, mapValue, opts, fullName)
  304. }
  305. }
  306. func (u *Unmarshaler) processNamedFieldWithoutValue(field reflect.StructField, value reflect.Value,
  307. opts *fieldOptionsWithContext, fullName string) error {
  308. derefedType := Deref(field.Type)
  309. fieldKind := derefedType.Kind()
  310. if defaultValue, ok := opts.getDefault(); ok {
  311. if field.Type.Kind() == reflect.Ptr {
  312. maybeNewValue(field, value)
  313. value = value.Elem()
  314. }
  315. if derefedType == durationType {
  316. return fillDurationValue(fieldKind, value, defaultValue)
  317. }
  318. return setValue(fieldKind, value, defaultValue)
  319. }
  320. switch fieldKind {
  321. case reflect.Array, reflect.Map, reflect.Slice:
  322. if !opts.optional() {
  323. return u.processFieldNotFromString(field, value, emptyMap, opts, fullName)
  324. }
  325. case reflect.Struct:
  326. if !opts.optional() {
  327. required, err := structValueRequired(u.key, derefedType)
  328. if err != nil {
  329. return err
  330. }
  331. if required {
  332. return fmt.Errorf("%q is not set", fullName)
  333. }
  334. return u.processFieldNotFromString(field, value, emptyMap, opts, fullName)
  335. }
  336. default:
  337. if !opts.optional() {
  338. return newInitError(fullName)
  339. }
  340. }
  341. return nil
  342. }
  343. func (u *Unmarshaler) fillMap(field reflect.StructField, value reflect.Value, mapValue interface{}) error {
  344. if !value.CanSet() {
  345. return errValueNotSettable
  346. }
  347. fieldKeyType := field.Type.Key()
  348. fieldElemType := field.Type.Elem()
  349. targetValue, err := u.generateMap(fieldKeyType, fieldElemType, mapValue)
  350. if err != nil {
  351. return err
  352. }
  353. value.Set(targetValue)
  354. return nil
  355. }
  356. func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
  357. if !value.CanSet() {
  358. return errValueNotSettable
  359. }
  360. baseType := fieldType.Elem()
  361. baseKind := baseType.Kind()
  362. dereffedBaseType := Deref(baseType)
  363. dereffedBaseKind := dereffedBaseType.Kind()
  364. refValue := reflect.ValueOf(mapValue)
  365. conv := reflect.MakeSlice(reflect.SliceOf(baseType), refValue.Len(), refValue.Cap())
  366. var valid bool
  367. for i := 0; i < refValue.Len(); i++ {
  368. ithValue := refValue.Index(i).Interface()
  369. if ithValue == nil {
  370. continue
  371. }
  372. valid = true
  373. switch dereffedBaseKind {
  374. case reflect.Struct:
  375. target := reflect.New(dereffedBaseType)
  376. if err := u.Unmarshal(ithValue.(map[string]interface{}), target.Interface()); err != nil {
  377. return err
  378. }
  379. if baseKind == reflect.Ptr {
  380. conv.Index(i).Set(target)
  381. } else {
  382. conv.Index(i).Set(target.Elem())
  383. }
  384. default:
  385. if err := u.fillSliceValue(conv, i, dereffedBaseKind, ithValue); err != nil {
  386. return err
  387. }
  388. }
  389. }
  390. if valid {
  391. value.Set(conv)
  392. }
  393. return nil
  394. }
  395. func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
  396. var slice []interface{}
  397. if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil {
  398. return err
  399. }
  400. baseFieldType := Deref(fieldType.Elem())
  401. baseFieldKind := baseFieldType.Kind()
  402. conv := reflect.MakeSlice(reflect.SliceOf(baseFieldType), len(slice), cap(slice))
  403. for i := 0; i < len(slice); i++ {
  404. if err := u.fillSliceValue(conv, i, baseFieldKind, slice[i]); err != nil {
  405. return err
  406. }
  407. }
  408. value.Set(conv)
  409. return nil
  410. }
  411. func (u *Unmarshaler) fillSliceValue(slice reflect.Value, index int, baseKind reflect.Kind, value interface{}) error {
  412. switch v := value.(type) {
  413. case json.Number:
  414. return setValue(baseKind, slice.Index(index), v.String())
  415. default:
  416. // don't need to consider the difference between int, int8, int16, int32, int64,
  417. // uint, uint8, uint16, uint32, uint64, because they're handled as json.Number.
  418. if slice.Index(index).Kind() != reflect.TypeOf(value).Kind() {
  419. return errTypeMismatch
  420. }
  421. slice.Index(index).Set(reflect.ValueOf(value))
  422. return nil
  423. }
  424. }
  425. func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue interface{}) (reflect.Value, error) {
  426. mapType := reflect.MapOf(keyType, elemType)
  427. valueType := reflect.TypeOf(mapValue)
  428. if mapType == valueType {
  429. return reflect.ValueOf(mapValue), nil
  430. }
  431. refValue := reflect.ValueOf(mapValue)
  432. targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
  433. fieldElemKind := elemType.Kind()
  434. dereffedElemType := Deref(elemType)
  435. dereffedElemKind := dereffedElemType.Kind()
  436. for _, key := range refValue.MapKeys() {
  437. keythValue := refValue.MapIndex(key)
  438. keythData := keythValue.Interface()
  439. switch dereffedElemKind {
  440. case reflect.Slice:
  441. target := reflect.New(dereffedElemType)
  442. if err := u.fillSlice(elemType, target.Elem(), keythData); err != nil {
  443. return emptyValue, err
  444. }
  445. targetValue.SetMapIndex(key, target.Elem())
  446. case reflect.Struct:
  447. keythMap, ok := keythData.(map[string]interface{})
  448. if !ok {
  449. return emptyValue, errTypeMismatch
  450. }
  451. target := reflect.New(dereffedElemType)
  452. if err := u.Unmarshal(keythMap, target.Interface()); err != nil {
  453. return emptyValue, err
  454. }
  455. if fieldElemKind == reflect.Ptr {
  456. targetValue.SetMapIndex(key, target)
  457. } else {
  458. targetValue.SetMapIndex(key, target.Elem())
  459. }
  460. case reflect.Map:
  461. keythMap, ok := keythData.(map[string]interface{})
  462. if !ok {
  463. return emptyValue, errTypeMismatch
  464. }
  465. innerValue, err := u.generateMap(elemType.Key(), elemType.Elem(), keythMap)
  466. if err != nil {
  467. return emptyValue, err
  468. }
  469. targetValue.SetMapIndex(key, innerValue)
  470. default:
  471. switch v := keythData.(type) {
  472. case string:
  473. targetValue.SetMapIndex(key, reflect.ValueOf(v))
  474. case json.Number:
  475. target := reflect.New(dereffedElemType)
  476. if err := setValue(dereffedElemKind, target.Elem(), v.String()); err != nil {
  477. return emptyValue, err
  478. }
  479. targetValue.SetMapIndex(key, target.Elem())
  480. default:
  481. targetValue.SetMapIndex(key, keythValue)
  482. }
  483. }
  484. }
  485. return targetValue, nil
  486. }
  487. func (u *Unmarshaler) parseOptionsWithContext(field reflect.StructField, m Valuer, fullName string) (
  488. string, *fieldOptionsWithContext, error) {
  489. key, options, err := parseKeyAndOptions(u.key, field)
  490. if err != nil {
  491. return "", nil, err
  492. } else if options == nil {
  493. return key, nil, nil
  494. }
  495. optsWithContext, err := options.toOptionsWithContext(key, m, fullName)
  496. if err != nil {
  497. return "", nil, err
  498. }
  499. return key, optsWithContext, nil
  500. }
  501. // WithStringValues customizes a Unmarshaler with number values from strings.
  502. func WithStringValues() UnmarshalOption {
  503. return func(opt *unmarshalOptions) {
  504. opt.fromString = true
  505. }
  506. }
  507. func fillDurationValue(fieldKind reflect.Kind, value reflect.Value, dur string) error {
  508. d, err := time.ParseDuration(dur)
  509. if err != nil {
  510. return err
  511. }
  512. if fieldKind == reflect.Ptr {
  513. value.Elem().Set(reflect.ValueOf(d))
  514. } else {
  515. value.Set(reflect.ValueOf(d))
  516. }
  517. return nil
  518. }
  519. func fillPrimitive(fieldType reflect.Type, value reflect.Value, mapValue interface{},
  520. opts *fieldOptionsWithContext, fullName string) error {
  521. if !value.CanSet() {
  522. return errValueNotSettable
  523. }
  524. baseType := Deref(fieldType)
  525. if fieldType.Kind() == reflect.Ptr {
  526. target := reflect.New(baseType).Elem()
  527. switch mapValue.(type) {
  528. case string, json.Number:
  529. value.Set(target.Addr())
  530. value = target
  531. }
  532. }
  533. switch v := mapValue.(type) {
  534. case string:
  535. return validateAndSetValue(baseType.Kind(), value, v, opts)
  536. case json.Number:
  537. if err := validateJsonNumberRange(v, opts); err != nil {
  538. return err
  539. }
  540. return setValue(baseType.Kind(), value, v.String())
  541. default:
  542. return newTypeMismatchError(fullName)
  543. }
  544. }
  545. func fillWithSameType(field reflect.StructField, value reflect.Value, mapValue interface{},
  546. opts *fieldOptionsWithContext) error {
  547. if !value.CanSet() {
  548. return errValueNotSettable
  549. }
  550. if err := validateValueRange(mapValue, opts); err != nil {
  551. return err
  552. }
  553. if field.Type.Kind() == reflect.Ptr {
  554. baseType := Deref(field.Type)
  555. target := reflect.New(baseType).Elem()
  556. target.Set(reflect.ValueOf(mapValue))
  557. value.Set(target.Addr())
  558. } else {
  559. value.Set(reflect.ValueOf(mapValue))
  560. }
  561. return nil
  562. }
  563. // getValue gets the value for the specific key, the key can be in the format of parentKey.childKey
  564. func getValue(m Valuer, key string) (interface{}, bool) {
  565. keys := readKeys(key)
  566. return getValueWithChainedKeys(m, keys)
  567. }
  568. func getValueWithChainedKeys(m Valuer, keys []string) (interface{}, bool) {
  569. if len(keys) == 1 {
  570. v, ok := m.Value(keys[0])
  571. return v, ok
  572. } else if len(keys) > 1 {
  573. if v, ok := m.Value(keys[0]); ok {
  574. if nextm, ok := v.(map[string]interface{}); ok {
  575. return getValueWithChainedKeys(MapValuer(nextm), keys[1:])
  576. }
  577. }
  578. }
  579. return nil, false
  580. }
  581. func insertKeys(key string, cache []string) {
  582. cacheKeysLock.Lock()
  583. defer cacheKeysLock.Unlock()
  584. keys := cacheKeys.Load().(keyCache)
  585. // copy the contents into the new map, to guarantee the old map is immutable
  586. newKeys := make(keyCache)
  587. for k, v := range keys {
  588. newKeys[k] = v
  589. }
  590. newKeys[key] = cache
  591. cacheKeys.Store(newKeys)
  592. }
  593. func join(elem ...string) string {
  594. var builder strings.Builder
  595. var fillSep bool
  596. for _, e := range elem {
  597. if len(e) == 0 {
  598. continue
  599. }
  600. if fillSep {
  601. builder.WriteByte(delimiter)
  602. } else {
  603. fillSep = true
  604. }
  605. builder.WriteString(e)
  606. }
  607. return builder.String()
  608. }
  609. func newInitError(name string) error {
  610. return fmt.Errorf("field %s is not set", name)
  611. }
  612. func newTypeMismatchError(name string) error {
  613. return fmt.Errorf("error: type mismatch for field %s", name)
  614. }
  615. func readKeys(key string) []string {
  616. cache := cacheKeys.Load().(keyCache)
  617. if keys, ok := cache[key]; ok {
  618. return keys
  619. }
  620. keys := strings.FieldsFunc(key, func(c rune) bool {
  621. return c == delimiter
  622. })
  623. insertKeys(key, keys)
  624. return keys
  625. }