utils.go 14 KB

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