unmarshaler.go 19 KB

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