utils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {
  124. numFields := tp.NumField()
  125. for i := 0; i < numFields; i++ {
  126. childField := tp.Field(i)
  127. if usingDifferentKeys(tag, childField) {
  128. return true, nil
  129. }
  130. _, opts, err := parseKeyAndOptions(tag, childField)
  131. if err != nil {
  132. return false, err
  133. }
  134. if opts == nil {
  135. if childField.Type.Kind() != reflect.Struct {
  136. return true, nil
  137. }
  138. if required, err := implicitValueRequiredStruct(tag, childField.Type); err != nil {
  139. return false, err
  140. } else if required {
  141. return true, nil
  142. }
  143. } else if !opts.Optional && len(opts.Default) == 0 {
  144. return true, nil
  145. } else if len(opts.OptionalDep) > 0 && opts.OptionalDep[0] == notSymbol {
  146. return true, nil
  147. }
  148. }
  149. return false, nil
  150. }
  151. func isLeftInclude(b byte) (bool, error) {
  152. switch b {
  153. case '[':
  154. return true, nil
  155. case '(':
  156. return false, nil
  157. default:
  158. return false, errNumberRange
  159. }
  160. }
  161. func isRightInclude(b byte) (bool, error) {
  162. switch b {
  163. case ']':
  164. return true, nil
  165. case ')':
  166. return false, nil
  167. default:
  168. return false, errNumberRange
  169. }
  170. }
  171. func maybeNewValue(field reflect.StructField, value reflect.Value) {
  172. if field.Type.Kind() == reflect.Ptr && value.IsNil() {
  173. value.Set(reflect.New(value.Type().Elem()))
  174. }
  175. }
  176. func parseGroupedSegments(val string) []string {
  177. val = strings.TrimLeftFunc(val, func(r rune) bool {
  178. return r == leftBracket || r == leftSquareBracket
  179. })
  180. val = strings.TrimRightFunc(val, func(r rune) bool {
  181. return r == rightBracket || r == rightSquareBracket
  182. })
  183. return parseSegments(val)
  184. }
  185. // don't modify returned fieldOptions, it's cached and shared among different calls.
  186. func parseKeyAndOptions(tagName string, field reflect.StructField) (string, *fieldOptions, error) {
  187. value := field.Tag.Get(tagName)
  188. if len(value) == 0 {
  189. return field.Name, nil, nil
  190. }
  191. cacheLock.RLock()
  192. cache, ok := optionsCache[value]
  193. cacheLock.RUnlock()
  194. if ok {
  195. return stringx.TakeOne(cache.key, field.Name), cache.options, cache.err
  196. }
  197. key, options, err := doParseKeyAndOptions(field, value)
  198. cacheLock.Lock()
  199. optionsCache[value] = optionsCacheValue{
  200. key: key,
  201. options: options,
  202. err: err,
  203. }
  204. cacheLock.Unlock()
  205. return stringx.TakeOne(key, field.Name), options, err
  206. }
  207. // support below notations:
  208. // [:5] (:5] [:5) (:5)
  209. // [1:] [1:) (1:] (1:)
  210. // [1:5] [1:5) (1:5] (1:5)
  211. func parseNumberRange(str string) (*numberRange, error) {
  212. if len(str) == 0 {
  213. return nil, errNumberRange
  214. }
  215. leftInclude, err := isLeftInclude(str[0])
  216. if err != nil {
  217. return nil, err
  218. }
  219. str = str[1:]
  220. if len(str) == 0 {
  221. return nil, errNumberRange
  222. }
  223. rightInclude, err := isRightInclude(str[len(str)-1])
  224. if err != nil {
  225. return nil, err
  226. }
  227. str = str[:len(str)-1]
  228. fields := strings.Split(str, ":")
  229. if len(fields) != 2 {
  230. return nil, errNumberRange
  231. }
  232. if len(fields[0]) == 0 && len(fields[1]) == 0 {
  233. return nil, errNumberRange
  234. }
  235. var left float64
  236. if len(fields[0]) > 0 {
  237. var err error
  238. if left, err = strconv.ParseFloat(fields[0], 64); err != nil {
  239. return nil, err
  240. }
  241. } else {
  242. left = -math.MaxFloat64
  243. }
  244. var right float64
  245. if len(fields[1]) > 0 {
  246. var err error
  247. if right, err = strconv.ParseFloat(fields[1], 64); err != nil {
  248. return nil, err
  249. }
  250. } else {
  251. right = math.MaxFloat64
  252. }
  253. return &numberRange{
  254. left: left,
  255. leftInclude: leftInclude,
  256. right: right,
  257. rightInclude: rightInclude,
  258. }, nil
  259. }
  260. func parseOption(fieldOpts *fieldOptions, fieldName, option string) error {
  261. switch {
  262. case option == stringOption:
  263. fieldOpts.FromString = true
  264. case strings.HasPrefix(option, optionalOption):
  265. segs := strings.Split(option, equalToken)
  266. switch len(segs) {
  267. case 1:
  268. fieldOpts.Optional = true
  269. case 2:
  270. fieldOpts.Optional = true
  271. fieldOpts.OptionalDep = segs[1]
  272. default:
  273. return fmt.Errorf("field %s has wrong optional", fieldName)
  274. }
  275. case option == optionalOption:
  276. fieldOpts.Optional = true
  277. case strings.HasPrefix(option, optionsOption):
  278. segs := strings.Split(option, equalToken)
  279. if len(segs) != 2 {
  280. return fmt.Errorf("field %s has wrong options", fieldName)
  281. }
  282. fieldOpts.Options = parseOptions(segs[1])
  283. case strings.HasPrefix(option, defaultOption):
  284. segs := strings.Split(option, equalToken)
  285. if len(segs) != 2 {
  286. return fmt.Errorf("field %s has wrong default option", fieldName)
  287. }
  288. fieldOpts.Default = strings.TrimSpace(segs[1])
  289. case strings.HasPrefix(option, rangeOption):
  290. segs := strings.Split(option, equalToken)
  291. if len(segs) != 2 {
  292. return fmt.Errorf("field %s has wrong range", fieldName)
  293. }
  294. nr, err := parseNumberRange(segs[1])
  295. if err != nil {
  296. return err
  297. }
  298. fieldOpts.Range = nr
  299. }
  300. return nil
  301. }
  302. // parseOptions parses the given options in tag.
  303. // for example: `json:"name,options=foo|bar"` or `json:"name,options=[foo,bar]"`
  304. func parseOptions(val string) []string {
  305. if len(val) == 0 {
  306. return nil
  307. }
  308. if val[0] == leftSquareBracket {
  309. return parseGroupedSegments(val)
  310. }
  311. return strings.Split(val, optionSeparator)
  312. }
  313. func parseSegments(val string) []string {
  314. var segments []string
  315. var escaped, grouped bool
  316. var buf strings.Builder
  317. for _, ch := range val {
  318. if escaped {
  319. buf.WriteRune(ch)
  320. escaped = false
  321. continue
  322. }
  323. switch ch {
  324. case segmentSeparator:
  325. if grouped {
  326. buf.WriteRune(ch)
  327. } else {
  328. // need to trim spaces, but we cannot ignore empty string,
  329. // because the first segment stands for the key might be empty.
  330. // if ignored, the later tag will be used as the key.
  331. segments = append(segments, strings.TrimSpace(buf.String()))
  332. buf.Reset()
  333. }
  334. case escapeChar:
  335. if grouped {
  336. buf.WriteRune(ch)
  337. } else {
  338. escaped = true
  339. }
  340. case leftBracket, leftSquareBracket:
  341. buf.WriteRune(ch)
  342. grouped = true
  343. case rightBracket, rightSquareBracket:
  344. buf.WriteRune(ch)
  345. grouped = false
  346. default:
  347. buf.WriteRune(ch)
  348. }
  349. }
  350. last := strings.TrimSpace(buf.String())
  351. // ignore last empty string
  352. if len(last) > 0 {
  353. segments = append(segments, last)
  354. }
  355. return segments
  356. }
  357. func reprOfValue(val reflect.Value) string {
  358. switch vt := val.Interface().(type) {
  359. case bool:
  360. return strconv.FormatBool(vt)
  361. case error:
  362. return vt.Error()
  363. case float32:
  364. return strconv.FormatFloat(float64(vt), 'f', -1, 32)
  365. case float64:
  366. return strconv.FormatFloat(vt, 'f', -1, 64)
  367. case fmt.Stringer:
  368. return vt.String()
  369. case int:
  370. return strconv.Itoa(vt)
  371. case int8:
  372. return strconv.Itoa(int(vt))
  373. case int16:
  374. return strconv.Itoa(int(vt))
  375. case int32:
  376. return strconv.Itoa(int(vt))
  377. case int64:
  378. return strconv.FormatInt(vt, 10)
  379. case string:
  380. return vt
  381. case uint:
  382. return strconv.FormatUint(uint64(vt), 10)
  383. case uint8:
  384. return strconv.FormatUint(uint64(vt), 10)
  385. case uint16:
  386. return strconv.FormatUint(uint64(vt), 10)
  387. case uint32:
  388. return strconv.FormatUint(uint64(vt), 10)
  389. case uint64:
  390. return strconv.FormatUint(vt, 10)
  391. case []byte:
  392. return string(vt)
  393. default:
  394. return fmt.Sprint(val.Interface())
  395. }
  396. }
  397. func setMatchedPrimitiveValue(kind reflect.Kind, value reflect.Value, v interface{}) error {
  398. switch kind {
  399. case reflect.Bool:
  400. value.SetBool(v.(bool))
  401. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  402. value.SetInt(v.(int64))
  403. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  404. value.SetUint(v.(uint64))
  405. case reflect.Float32, reflect.Float64:
  406. value.SetFloat(v.(float64))
  407. case reflect.String:
  408. value.SetString(v.(string))
  409. default:
  410. return errUnsupportedType
  411. }
  412. return nil
  413. }
  414. func setValue(kind reflect.Kind, value reflect.Value, str string) error {
  415. if !value.CanSet() {
  416. return errValueNotSettable
  417. }
  418. v, err := convertType(kind, str)
  419. if err != nil {
  420. return err
  421. }
  422. return setMatchedPrimitiveValue(kind, value, v)
  423. }
  424. func structValueRequired(tag string, tp reflect.Type) (bool, error) {
  425. structCacheLock.RLock()
  426. val, ok := structRequiredCache[tp]
  427. structCacheLock.RUnlock()
  428. if ok {
  429. return val.required, val.err
  430. }
  431. required, err := implicitValueRequiredStruct(tag, tp)
  432. structCacheLock.Lock()
  433. structRequiredCache[tp] = requiredCacheValue{
  434. required: required,
  435. err: err,
  436. }
  437. structCacheLock.Unlock()
  438. return required, err
  439. }
  440. func toFloat64(v interface{}) (float64, bool) {
  441. switch val := v.(type) {
  442. case int:
  443. return float64(val), true
  444. case int8:
  445. return float64(val), true
  446. case int16:
  447. return float64(val), true
  448. case int32:
  449. return float64(val), true
  450. case int64:
  451. return float64(val), true
  452. case uint:
  453. return float64(val), true
  454. case uint8:
  455. return float64(val), true
  456. case uint16:
  457. return float64(val), true
  458. case uint32:
  459. return float64(val), true
  460. case uint64:
  461. return float64(val), true
  462. case float32:
  463. return float64(val), true
  464. case float64:
  465. return val, true
  466. default:
  467. return 0, false
  468. }
  469. }
  470. func usingDifferentKeys(key string, field reflect.StructField) bool {
  471. if len(field.Tag) > 0 {
  472. if _, ok := field.Tag.Lookup(key); !ok {
  473. return true
  474. }
  475. }
  476. return false
  477. }
  478. func validateAndSetValue(kind reflect.Kind, value reflect.Value, str string, opts *fieldOptionsWithContext) error {
  479. if !value.CanSet() {
  480. return errValueNotSettable
  481. }
  482. v, err := convertType(kind, str)
  483. if err != nil {
  484. return err
  485. }
  486. if err := validateValueRange(v, opts); err != nil {
  487. return err
  488. }
  489. return setMatchedPrimitiveValue(kind, value, v)
  490. }
  491. func validateJsonNumberRange(v json.Number, opts *fieldOptionsWithContext) error {
  492. if opts == nil || opts.Range == nil {
  493. return nil
  494. }
  495. fv, err := v.Float64()
  496. if err != nil {
  497. return err
  498. }
  499. return validateNumberRange(fv, opts.Range)
  500. }
  501. func validateNumberRange(fv float64, nr *numberRange) error {
  502. if nr == nil {
  503. return nil
  504. }
  505. if (nr.leftInclude && fv < nr.left) || (!nr.leftInclude && fv <= nr.left) {
  506. return errNumberRange
  507. }
  508. if (nr.rightInclude && fv > nr.right) || (!nr.rightInclude && fv >= nr.right) {
  509. return errNumberRange
  510. }
  511. return nil
  512. }
  513. func validateValueInOptions(val interface{}, options []string) error {
  514. if len(options) > 0 {
  515. switch v := val.(type) {
  516. case string:
  517. if !stringx.Contains(options, v) {
  518. return fmt.Errorf(`error: value "%s" is not defined in options "%v"`, v, options)
  519. }
  520. default:
  521. if !stringx.Contains(options, Repr(v)) {
  522. return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, val, options)
  523. }
  524. }
  525. }
  526. return nil
  527. }
  528. func validateValueRange(mapValue interface{}, opts *fieldOptionsWithContext) error {
  529. if opts == nil || opts.Range == nil {
  530. return nil
  531. }
  532. fv, ok := toFloat64(mapValue)
  533. if !ok {
  534. return errNumberRange
  535. }
  536. return validateNumberRange(fv, opts.Range)
  537. }