utils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. package mapping
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/zeromicro/go-zero/core/lang"
  12. "github.com/zeromicro/go-zero/core/stringx"
  13. )
  14. const (
  15. defaultOption = "default"
  16. envOption = "env"
  17. inheritOption = "inherit"
  18. stringOption = "string"
  19. optionalOption = "optional"
  20. optionsOption = "options"
  21. rangeOption = "range"
  22. optionSeparator = "|"
  23. equalToken = "="
  24. escapeChar = '\\'
  25. leftBracket = '('
  26. rightBracket = ')'
  27. leftSquareBracket = '['
  28. rightSquareBracket = ']'
  29. segmentSeparator = ','
  30. )
  31. var (
  32. errUnsupportedType = errors.New("unsupported type on setting field value")
  33. errNumberRange = errors.New("wrong number range setting")
  34. optionsCache = make(map[string]optionsCacheValue)
  35. cacheLock sync.RWMutex
  36. structRequiredCache = make(map[reflect.Type]requiredCacheValue)
  37. structCacheLock sync.RWMutex
  38. )
  39. type (
  40. optionsCacheValue struct {
  41. key string
  42. options *fieldOptions
  43. err error
  44. }
  45. requiredCacheValue struct {
  46. required bool
  47. err error
  48. }
  49. )
  50. // Deref dereferences a type, if pointer type, returns its element type.
  51. func Deref(t reflect.Type) reflect.Type {
  52. for t.Kind() == reflect.Ptr {
  53. t = t.Elem()
  54. }
  55. return t
  56. }
  57. // Repr returns the string representation of v.
  58. func Repr(v any) string {
  59. return lang.Repr(v)
  60. }
  61. // SetValue sets target to value, pointers are processed automatically.
  62. func SetValue(tp reflect.Type, value, target reflect.Value) {
  63. value.Set(convertTypeOfPtr(tp, target))
  64. }
  65. // SetMapIndexValue sets target to value at key position, pointers are processed automatically.
  66. func SetMapIndexValue(tp reflect.Type, value, key, target reflect.Value) {
  67. value.SetMapIndex(key, convertTypeOfPtr(tp, target))
  68. }
  69. // ValidatePtr validates v if it's a valid pointer.
  70. func ValidatePtr(v *reflect.Value) error {
  71. // sequence is very important, IsNil must be called after checking Kind() with reflect.Ptr,
  72. // panic otherwise
  73. if !v.IsValid() || v.Kind() != reflect.Ptr || v.IsNil() {
  74. return fmt.Errorf("not a valid pointer: %v", v)
  75. }
  76. return nil
  77. }
  78. func convertTypeFromString(kind reflect.Kind, str string) (any, error) {
  79. switch kind {
  80. case reflect.Bool:
  81. switch strings.ToLower(str) {
  82. case "1", "true":
  83. return true, nil
  84. case "0", "false":
  85. return false, nil
  86. default:
  87. return false, errTypeMismatch
  88. }
  89. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  90. intValue, err := strconv.ParseInt(str, 10, 64)
  91. if err != nil {
  92. return 0, fmt.Errorf("the value %q cannot parsed as int", str)
  93. }
  94. return intValue, nil
  95. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  96. uintValue, err := strconv.ParseUint(str, 10, 64)
  97. if err != nil {
  98. return 0, fmt.Errorf("the value %q cannot parsed as uint", str)
  99. }
  100. return uintValue, nil
  101. case reflect.Float32, reflect.Float64:
  102. floatValue, err := strconv.ParseFloat(str, 64)
  103. if err != nil {
  104. return 0, fmt.Errorf("the value %q cannot parsed as float", str)
  105. }
  106. return floatValue, nil
  107. case reflect.String:
  108. return str, nil
  109. default:
  110. return nil, errUnsupportedType
  111. }
  112. }
  113. func convertTypeOfPtr(tp reflect.Type, target reflect.Value) reflect.Value {
  114. // keep the original value is a pointer
  115. if tp.Kind() == reflect.Ptr && target.CanAddr() {
  116. tp = tp.Elem()
  117. target = target.Addr()
  118. }
  119. for tp.Kind() == reflect.Ptr {
  120. p := reflect.New(target.Type())
  121. p.Elem().Set(target)
  122. target = p
  123. tp = tp.Elem()
  124. }
  125. return target
  126. }
  127. func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fieldOptions, error) {
  128. segments := parseSegments(value)
  129. key := strings.TrimSpace(segments[0])
  130. options := segments[1:]
  131. if len(options) == 0 {
  132. return key, nil, nil
  133. }
  134. var fieldOpts fieldOptions
  135. for _, segment := range options {
  136. option := strings.TrimSpace(segment)
  137. if err := parseOption(&fieldOpts, field.Name, option); err != nil {
  138. return "", nil, err
  139. }
  140. }
  141. return key, &fieldOpts, nil
  142. }
  143. // ensureValue ensures nested members not to be nil.
  144. // If pointer value is nil, set to a new value.
  145. func ensureValue(v reflect.Value) reflect.Value {
  146. for {
  147. if v.Kind() != reflect.Ptr {
  148. break
  149. }
  150. if v.IsNil() {
  151. v.Set(reflect.New(v.Type().Elem()))
  152. }
  153. v = v.Elem()
  154. }
  155. return v
  156. }
  157. func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {
  158. numFields := tp.NumField()
  159. for i := 0; i < numFields; i++ {
  160. childField := tp.Field(i)
  161. if usingDifferentKeys(tag, childField) {
  162. return true, nil
  163. }
  164. _, opts, err := parseKeyAndOptions(tag, childField)
  165. if err != nil {
  166. return false, err
  167. }
  168. if opts == nil {
  169. if childField.Type.Kind() != reflect.Struct {
  170. return true, nil
  171. }
  172. if required, err := implicitValueRequiredStruct(tag, childField.Type); err != nil {
  173. return false, err
  174. } else if required {
  175. return true, nil
  176. }
  177. } else if !opts.Optional && len(opts.Default) == 0 {
  178. return true, nil
  179. } else if len(opts.OptionalDep) > 0 && opts.OptionalDep[0] == notSymbol {
  180. return true, nil
  181. }
  182. }
  183. return false, nil
  184. }
  185. func isLeftInclude(b byte) (bool, error) {
  186. switch b {
  187. case '[':
  188. return true, nil
  189. case '(':
  190. return false, nil
  191. default:
  192. return false, errNumberRange
  193. }
  194. }
  195. func isRightInclude(b byte) (bool, error) {
  196. switch b {
  197. case ']':
  198. return true, nil
  199. case ')':
  200. return false, nil
  201. default:
  202. return false, errNumberRange
  203. }
  204. }
  205. func maybeNewValue(fieldType reflect.Type, value reflect.Value) {
  206. if fieldType.Kind() == reflect.Ptr && value.IsNil() {
  207. value.Set(reflect.New(value.Type().Elem()))
  208. }
  209. }
  210. func parseGroupedSegments(val string) []string {
  211. val = strings.TrimLeftFunc(val, func(r rune) bool {
  212. return r == leftBracket || r == leftSquareBracket
  213. })
  214. val = strings.TrimRightFunc(val, func(r rune) bool {
  215. return r == rightBracket || r == rightSquareBracket
  216. })
  217. return parseSegments(val)
  218. }
  219. // don't modify returned fieldOptions, it's cached and shared among different calls.
  220. func parseKeyAndOptions(tagName string, field reflect.StructField) (string, *fieldOptions, error) {
  221. value := field.Tag.Get(tagName)
  222. if len(value) == 0 {
  223. return field.Name, nil, nil
  224. }
  225. cacheLock.RLock()
  226. cache, ok := optionsCache[value]
  227. cacheLock.RUnlock()
  228. if ok {
  229. return stringx.TakeOne(cache.key, field.Name), cache.options, cache.err
  230. }
  231. key, options, err := doParseKeyAndOptions(field, value)
  232. cacheLock.Lock()
  233. optionsCache[value] = optionsCacheValue{
  234. key: key,
  235. options: options,
  236. err: err,
  237. }
  238. cacheLock.Unlock()
  239. return stringx.TakeOne(key, field.Name), options, err
  240. }
  241. // support below notations:
  242. // [:5] (:5] [:5) (:5)
  243. // [1:] [1:) (1:] (1:)
  244. // [1:5] [1:5) (1:5] (1:5)
  245. func parseNumberRange(str string) (*numberRange, error) {
  246. if len(str) == 0 {
  247. return nil, errNumberRange
  248. }
  249. leftInclude, err := isLeftInclude(str[0])
  250. if err != nil {
  251. return nil, err
  252. }
  253. str = str[1:]
  254. if len(str) == 0 {
  255. return nil, errNumberRange
  256. }
  257. rightInclude, err := isRightInclude(str[len(str)-1])
  258. if err != nil {
  259. return nil, err
  260. }
  261. str = str[:len(str)-1]
  262. fields := strings.Split(str, ":")
  263. if len(fields) != 2 {
  264. return nil, errNumberRange
  265. }
  266. if len(fields[0]) == 0 && len(fields[1]) == 0 {
  267. return nil, errNumberRange
  268. }
  269. var left float64
  270. if len(fields[0]) > 0 {
  271. var err error
  272. if left, err = strconv.ParseFloat(fields[0], 64); err != nil {
  273. return nil, err
  274. }
  275. } else {
  276. left = -math.MaxFloat64
  277. }
  278. var right float64
  279. if len(fields[1]) > 0 {
  280. var err error
  281. if right, err = strconv.ParseFloat(fields[1], 64); err != nil {
  282. return nil, err
  283. }
  284. } else {
  285. right = math.MaxFloat64
  286. }
  287. if left > right {
  288. return nil, errNumberRange
  289. }
  290. // [2:2] valid
  291. // [2:2) invalid
  292. // (2:2] invalid
  293. // (2:2) invalid
  294. if left == right {
  295. if !leftInclude || !rightInclude {
  296. return nil, errNumberRange
  297. }
  298. }
  299. return &numberRange{
  300. left: left,
  301. leftInclude: leftInclude,
  302. right: right,
  303. rightInclude: rightInclude,
  304. }, nil
  305. }
  306. func parseOption(fieldOpts *fieldOptions, fieldName, option string) error {
  307. switch {
  308. case option == inheritOption:
  309. fieldOpts.Inherit = true
  310. case option == stringOption:
  311. fieldOpts.FromString = true
  312. case strings.HasPrefix(option, optionalOption):
  313. segs := strings.Split(option, equalToken)
  314. switch len(segs) {
  315. case 1:
  316. fieldOpts.Optional = true
  317. case 2:
  318. fieldOpts.Optional = true
  319. fieldOpts.OptionalDep = segs[1]
  320. default:
  321. return fmt.Errorf("field %s has wrong optional", fieldName)
  322. }
  323. case option == optionalOption:
  324. fieldOpts.Optional = true
  325. case strings.HasPrefix(option, optionsOption):
  326. val, err := parseProperty(fieldName, optionsOption, option)
  327. if err != nil {
  328. return err
  329. }
  330. fieldOpts.Options = parseOptions(val)
  331. case strings.HasPrefix(option, defaultOption):
  332. val, err := parseProperty(fieldName, defaultOption, option)
  333. if err != nil {
  334. return err
  335. }
  336. fieldOpts.Default = val
  337. case strings.HasPrefix(option, envOption):
  338. val, err := parseProperty(fieldName, envOption, option)
  339. if err != nil {
  340. return err
  341. }
  342. fieldOpts.EnvVar = val
  343. case strings.HasPrefix(option, rangeOption):
  344. val, err := parseProperty(fieldName, rangeOption, option)
  345. if err != nil {
  346. return err
  347. }
  348. nr, err := parseNumberRange(val)
  349. if err != nil {
  350. return err
  351. }
  352. fieldOpts.Range = nr
  353. }
  354. return nil
  355. }
  356. // parseOptions parses the given options in tag.
  357. // for example: `json:"name,options=foo|bar"` or `json:"name,options=[foo,bar]"`
  358. func parseOptions(val string) []string {
  359. if len(val) == 0 {
  360. return nil
  361. }
  362. if val[0] == leftSquareBracket {
  363. return parseGroupedSegments(val)
  364. }
  365. return strings.Split(val, optionSeparator)
  366. }
  367. func parseProperty(field, tag, val string) (string, error) {
  368. segs := strings.Split(val, equalToken)
  369. if len(segs) != 2 {
  370. return "", fmt.Errorf("field %s has wrong %s", field, tag)
  371. }
  372. return strings.TrimSpace(segs[1]), nil
  373. }
  374. func parseSegments(val string) []string {
  375. var segments []string
  376. var escaped, grouped bool
  377. var buf strings.Builder
  378. for _, ch := range val {
  379. if escaped {
  380. buf.WriteRune(ch)
  381. escaped = false
  382. continue
  383. }
  384. switch ch {
  385. case segmentSeparator:
  386. if grouped {
  387. buf.WriteRune(ch)
  388. } else {
  389. // need to trim spaces, but we cannot ignore empty string,
  390. // because the first segment stands for the key might be empty.
  391. // if ignored, the later tag will be used as the key.
  392. segments = append(segments, strings.TrimSpace(buf.String()))
  393. buf.Reset()
  394. }
  395. case escapeChar:
  396. if grouped {
  397. buf.WriteRune(ch)
  398. } else {
  399. escaped = true
  400. }
  401. case leftBracket, leftSquareBracket:
  402. buf.WriteRune(ch)
  403. grouped = true
  404. case rightBracket, rightSquareBracket:
  405. buf.WriteRune(ch)
  406. grouped = false
  407. default:
  408. buf.WriteRune(ch)
  409. }
  410. }
  411. last := strings.TrimSpace(buf.String())
  412. // ignore last empty string
  413. if len(last) > 0 {
  414. segments = append(segments, last)
  415. }
  416. return segments
  417. }
  418. func setMatchedPrimitiveValue(kind reflect.Kind, value reflect.Value, v any) error {
  419. switch kind {
  420. case reflect.Bool:
  421. value.SetBool(v.(bool))
  422. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  423. value.SetInt(v.(int64))
  424. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  425. value.SetUint(v.(uint64))
  426. case reflect.Float32, reflect.Float64:
  427. value.SetFloat(v.(float64))
  428. case reflect.String:
  429. value.SetString(v.(string))
  430. default:
  431. return errUnsupportedType
  432. }
  433. return nil
  434. }
  435. func setValueFromString(kind reflect.Kind, value reflect.Value, str string) error {
  436. if !value.CanSet() {
  437. return errValueNotSettable
  438. }
  439. value = ensureValue(value)
  440. v, err := convertTypeFromString(kind, str)
  441. if err != nil {
  442. return err
  443. }
  444. return setMatchedPrimitiveValue(kind, value, v)
  445. }
  446. func structValueRequired(tag string, tp reflect.Type) (bool, error) {
  447. structCacheLock.RLock()
  448. val, ok := structRequiredCache[tp]
  449. structCacheLock.RUnlock()
  450. if ok {
  451. return val.required, val.err
  452. }
  453. required, err := implicitValueRequiredStruct(tag, tp)
  454. structCacheLock.Lock()
  455. structRequiredCache[tp] = requiredCacheValue{
  456. required: required,
  457. err: err,
  458. }
  459. structCacheLock.Unlock()
  460. return required, err
  461. }
  462. func toFloat64(v any) (float64, bool) {
  463. switch val := v.(type) {
  464. case int:
  465. return float64(val), true
  466. case int8:
  467. return float64(val), true
  468. case int16:
  469. return float64(val), true
  470. case int32:
  471. return float64(val), true
  472. case int64:
  473. return float64(val), true
  474. case uint:
  475. return float64(val), true
  476. case uint8:
  477. return float64(val), true
  478. case uint16:
  479. return float64(val), true
  480. case uint32:
  481. return float64(val), true
  482. case uint64:
  483. return float64(val), true
  484. case float32:
  485. return float64(val), true
  486. case float64:
  487. return val, true
  488. default:
  489. return 0, false
  490. }
  491. }
  492. func usingDifferentKeys(key string, field reflect.StructField) bool {
  493. if len(field.Tag) > 0 {
  494. if _, ok := field.Tag.Lookup(key); !ok {
  495. return true
  496. }
  497. }
  498. return false
  499. }
  500. func validateAndSetValue(kind reflect.Kind, value reflect.Value, str string, opts *fieldOptionsWithContext) error {
  501. if !value.CanSet() {
  502. return errValueNotSettable
  503. }
  504. v, err := convertTypeFromString(kind, str)
  505. if err != nil {
  506. return err
  507. }
  508. if err := validateValueRange(v, opts); err != nil {
  509. return err
  510. }
  511. return setMatchedPrimitiveValue(kind, value, v)
  512. }
  513. func validateJsonNumberRange(v json.Number, opts *fieldOptionsWithContext) error {
  514. if opts == nil || opts.Range == nil {
  515. return nil
  516. }
  517. fv, err := v.Float64()
  518. if err != nil {
  519. return err
  520. }
  521. return validateNumberRange(fv, opts.Range)
  522. }
  523. func validateNumberRange(fv float64, nr *numberRange) error {
  524. if nr == nil {
  525. return nil
  526. }
  527. if (nr.leftInclude && fv < nr.left) || (!nr.leftInclude && fv <= nr.left) {
  528. return errNumberRange
  529. }
  530. if (nr.rightInclude && fv > nr.right) || (!nr.rightInclude && fv >= nr.right) {
  531. return errNumberRange
  532. }
  533. return nil
  534. }
  535. func validateValueInOptions(val any, options []string) error {
  536. if len(options) > 0 {
  537. switch v := val.(type) {
  538. case string:
  539. if !stringx.Contains(options, v) {
  540. return fmt.Errorf(`error: value "%s" is not defined in options "%v"`, v, options)
  541. }
  542. default:
  543. if !stringx.Contains(options, Repr(v)) {
  544. return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, val, options)
  545. }
  546. }
  547. }
  548. return nil
  549. }
  550. func validateValueRange(mapValue any, opts *fieldOptionsWithContext) error {
  551. if opts == nil || opts.Range == nil {
  552. return nil
  553. }
  554. fv, ok := toFloat64(mapValue)
  555. if !ok {
  556. return errNumberRange
  557. }
  558. return validateNumberRange(fv, opts.Range)
  559. }