utils.go 13 KB

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