utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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/tal-tech/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. )
  22. var (
  23. errUnsupportedType = errors.New("unsupported type on setting field value")
  24. errNumberRange = errors.New("wrong number range setting")
  25. optionsCache = make(map[string]optionsCacheValue)
  26. cacheLock sync.RWMutex
  27. structRequiredCache = make(map[reflect.Type]requiredCacheValue)
  28. structCacheLock sync.RWMutex
  29. )
  30. type (
  31. optionsCacheValue struct {
  32. key string
  33. options *fieldOptions
  34. err error
  35. }
  36. requiredCacheValue struct {
  37. required bool
  38. err error
  39. }
  40. )
  41. func Deref(t reflect.Type) reflect.Type {
  42. if t.Kind() == reflect.Ptr {
  43. t = t.Elem()
  44. }
  45. return t
  46. }
  47. func Repr(v interface{}) string {
  48. if v == nil {
  49. return ""
  50. }
  51. // if func (v *Type) String() string, we can't use Elem()
  52. switch vt := v.(type) {
  53. case fmt.Stringer:
  54. return vt.String()
  55. }
  56. val := reflect.ValueOf(v)
  57. if val.Kind() == reflect.Ptr && !val.IsNil() {
  58. val = val.Elem()
  59. }
  60. switch vt := val.Interface().(type) {
  61. case bool:
  62. return strconv.FormatBool(vt)
  63. case error:
  64. return vt.Error()
  65. case float32:
  66. return strconv.FormatFloat(float64(vt), 'f', -1, 32)
  67. case float64:
  68. return strconv.FormatFloat(vt, 'f', -1, 64)
  69. case fmt.Stringer:
  70. return vt.String()
  71. case int:
  72. return strconv.Itoa(vt)
  73. case int8:
  74. return strconv.Itoa(int(vt))
  75. case int16:
  76. return strconv.Itoa(int(vt))
  77. case int32:
  78. return strconv.Itoa(int(vt))
  79. case int64:
  80. return strconv.FormatInt(vt, 10)
  81. case string:
  82. return vt
  83. case uint:
  84. return strconv.FormatUint(uint64(vt), 10)
  85. case uint8:
  86. return strconv.FormatUint(uint64(vt), 10)
  87. case uint16:
  88. return strconv.FormatUint(uint64(vt), 10)
  89. case uint32:
  90. return strconv.FormatUint(uint64(vt), 10)
  91. case uint64:
  92. return strconv.FormatUint(vt, 10)
  93. case []byte:
  94. return string(vt)
  95. default:
  96. return fmt.Sprint(val.Interface())
  97. }
  98. }
  99. func ValidatePtr(v *reflect.Value) error {
  100. // sequence is very important, IsNil must be called after checking Kind() with reflect.Ptr,
  101. // panic otherwise
  102. if !v.IsValid() || v.Kind() != reflect.Ptr || v.IsNil() {
  103. return fmt.Errorf("not a valid pointer: %v", v)
  104. }
  105. return nil
  106. }
  107. func convertType(kind reflect.Kind, str string) (interface{}, error) {
  108. switch kind {
  109. case reflect.Bool:
  110. return str == "1" || strings.ToLower(str) == "true", nil
  111. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  112. intValue, err := strconv.ParseInt(str, 10, 64)
  113. if err != nil {
  114. return 0, fmt.Errorf("the value %q cannot parsed as int", str)
  115. }
  116. return intValue, nil
  117. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  118. uintValue, err := strconv.ParseUint(str, 10, 64)
  119. if err != nil {
  120. return 0, fmt.Errorf("the value %q cannot parsed as uint", str)
  121. }
  122. return uintValue, nil
  123. case reflect.Float32, reflect.Float64:
  124. floatValue, err := strconv.ParseFloat(str, 64)
  125. if err != nil {
  126. return 0, fmt.Errorf("the value %q cannot parsed as float", str)
  127. }
  128. return floatValue, nil
  129. case reflect.String:
  130. return str, nil
  131. default:
  132. return nil, errUnsupportedType
  133. }
  134. }
  135. func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fieldOptions, error) {
  136. segments := strings.Split(value, ",")
  137. key := strings.TrimSpace(segments[0])
  138. options := segments[1:]
  139. if len(options) == 0 {
  140. return key, nil, nil
  141. }
  142. var fieldOpts fieldOptions
  143. for _, segment := range options {
  144. option := strings.TrimSpace(segment)
  145. switch {
  146. case option == stringOption:
  147. fieldOpts.FromString = true
  148. case strings.HasPrefix(option, optionalOption):
  149. segs := strings.Split(option, equalToken)
  150. switch len(segs) {
  151. case 1:
  152. fieldOpts.Optional = true
  153. case 2:
  154. fieldOpts.Optional = true
  155. fieldOpts.OptionalDep = segs[1]
  156. default:
  157. return "", nil, fmt.Errorf("field %s has wrong optional", field.Name)
  158. }
  159. case option == optionalOption:
  160. fieldOpts.Optional = true
  161. case strings.HasPrefix(option, optionsOption):
  162. segs := strings.Split(option, equalToken)
  163. if len(segs) != 2 {
  164. return "", nil, fmt.Errorf("field %s has wrong options", field.Name)
  165. }
  166. fieldOpts.Options = strings.Split(segs[1], optionSeparator)
  167. case strings.HasPrefix(option, defaultOption):
  168. segs := strings.Split(option, equalToken)
  169. if len(segs) != 2 {
  170. return "", nil, fmt.Errorf("field %s has wrong default option", field.Name)
  171. }
  172. fieldOpts.Default = strings.TrimSpace(segs[1])
  173. case strings.HasPrefix(option, rangeOption):
  174. segs := strings.Split(option, equalToken)
  175. if len(segs) != 2 {
  176. return "", nil, fmt.Errorf("field %s has wrong range", field.Name)
  177. }
  178. nr, err := parseNumberRange(segs[1])
  179. if err != nil {
  180. return "", nil, err
  181. }
  182. fieldOpts.Range = nr
  183. }
  184. }
  185. return key, &fieldOpts, nil
  186. }
  187. func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {
  188. numFields := tp.NumField()
  189. for i := 0; i < numFields; i++ {
  190. childField := tp.Field(i)
  191. if usingDifferentKeys(tag, childField) {
  192. return true, nil
  193. }
  194. _, opts, err := parseKeyAndOptions(tag, childField)
  195. if err != nil {
  196. return false, err
  197. }
  198. if opts == nil {
  199. if childField.Type.Kind() != reflect.Struct {
  200. return true, nil
  201. }
  202. if required, err := implicitValueRequiredStruct(tag, childField.Type); err != nil {
  203. return false, err
  204. } else if required {
  205. return true, nil
  206. }
  207. } else if !opts.Optional && len(opts.Default) == 0 {
  208. return true, nil
  209. } else if len(opts.OptionalDep) > 0 && opts.OptionalDep[0] == notSymbol {
  210. return true, nil
  211. }
  212. }
  213. return false, nil
  214. }
  215. func maybeNewValue(field reflect.StructField, value reflect.Value) {
  216. if field.Type.Kind() == reflect.Ptr && value.IsNil() {
  217. value.Set(reflect.New(value.Type().Elem()))
  218. }
  219. }
  220. // don't modify returned fieldOptions, it's cached and shared among different calls.
  221. func parseKeyAndOptions(tagName string, field reflect.StructField) (string, *fieldOptions, error) {
  222. value := field.Tag.Get(tagName)
  223. if len(value) == 0 {
  224. return field.Name, nil, nil
  225. }
  226. cacheLock.RLock()
  227. cache, ok := optionsCache[value]
  228. cacheLock.RUnlock()
  229. if ok {
  230. return stringx.TakeOne(cache.key, field.Name), cache.options, cache.err
  231. }
  232. key, options, err := doParseKeyAndOptions(field, value)
  233. cacheLock.Lock()
  234. optionsCache[value] = optionsCacheValue{
  235. key: key,
  236. options: options,
  237. err: err,
  238. }
  239. cacheLock.Unlock()
  240. return stringx.TakeOne(key, field.Name), options, err
  241. }
  242. // support below notations:
  243. // [:5] (:5] [:5) (:5)
  244. // [1:] [1:) (1:] (1:)
  245. // [1:5] [1:5) (1:5] (1:5)
  246. func parseNumberRange(str string) (*numberRange, error) {
  247. if len(str) == 0 {
  248. return nil, errNumberRange
  249. }
  250. var leftInclude bool
  251. switch str[0] {
  252. case '[':
  253. leftInclude = true
  254. case '(':
  255. leftInclude = false
  256. default:
  257. return nil, errNumberRange
  258. }
  259. str = str[1:]
  260. if len(str) == 0 {
  261. return nil, errNumberRange
  262. }
  263. var rightInclude bool
  264. switch str[len(str)-1] {
  265. case ']':
  266. rightInclude = true
  267. case ')':
  268. rightInclude = false
  269. default:
  270. return nil, errNumberRange
  271. }
  272. str = str[:len(str)-1]
  273. fields := strings.Split(str, ":")
  274. if len(fields) != 2 {
  275. return nil, errNumberRange
  276. }
  277. if len(fields[0]) == 0 && len(fields[1]) == 0 {
  278. return nil, errNumberRange
  279. }
  280. var left float64
  281. if len(fields[0]) > 0 {
  282. var err error
  283. if left, err = strconv.ParseFloat(fields[0], 64); err != nil {
  284. return nil, err
  285. }
  286. } else {
  287. left = -math.MaxFloat64
  288. }
  289. var right float64
  290. if len(fields[1]) > 0 {
  291. var err error
  292. if right, err = strconv.ParseFloat(fields[1], 64); err != nil {
  293. return nil, err
  294. }
  295. } else {
  296. right = math.MaxFloat64
  297. }
  298. return &numberRange{
  299. left: left,
  300. leftInclude: leftInclude,
  301. right: right,
  302. rightInclude: rightInclude,
  303. }, nil
  304. }
  305. func setMatchedPrimitiveValue(kind reflect.Kind, value reflect.Value, v interface{}) error {
  306. switch kind {
  307. case reflect.Bool:
  308. value.SetBool(v.(bool))
  309. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  310. value.SetInt(v.(int64))
  311. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  312. value.SetUint(v.(uint64))
  313. case reflect.Float32, reflect.Float64:
  314. value.SetFloat(v.(float64))
  315. case reflect.String:
  316. value.SetString(v.(string))
  317. default:
  318. return errUnsupportedType
  319. }
  320. return nil
  321. }
  322. func setValue(kind reflect.Kind, value reflect.Value, str string) error {
  323. if !value.CanSet() {
  324. return errValueNotSettable
  325. }
  326. v, err := convertType(kind, str)
  327. if err != nil {
  328. return err
  329. }
  330. return setMatchedPrimitiveValue(kind, value, v)
  331. }
  332. func structValueRequired(tag string, tp reflect.Type) (bool, error) {
  333. structCacheLock.RLock()
  334. val, ok := structRequiredCache[tp]
  335. structCacheLock.RUnlock()
  336. if ok {
  337. return val.required, val.err
  338. }
  339. required, err := implicitValueRequiredStruct(tag, tp)
  340. structCacheLock.Lock()
  341. structRequiredCache[tp] = requiredCacheValue{
  342. required: required,
  343. err: err,
  344. }
  345. structCacheLock.Unlock()
  346. return required, err
  347. }
  348. func toFloat64(v interface{}) (float64, bool) {
  349. switch val := v.(type) {
  350. case int:
  351. return float64(val), true
  352. case int8:
  353. return float64(val), true
  354. case int16:
  355. return float64(val), true
  356. case int32:
  357. return float64(val), true
  358. case int64:
  359. return float64(val), true
  360. case uint:
  361. return float64(val), true
  362. case uint8:
  363. return float64(val), true
  364. case uint16:
  365. return float64(val), true
  366. case uint32:
  367. return float64(val), true
  368. case uint64:
  369. return float64(val), true
  370. case float32:
  371. return float64(val), true
  372. case float64:
  373. return val, true
  374. default:
  375. return 0, false
  376. }
  377. }
  378. func usingDifferentKeys(key string, field reflect.StructField) bool {
  379. if len(field.Tag) > 0 {
  380. if _, ok := field.Tag.Lookup(key); !ok {
  381. return true
  382. }
  383. }
  384. return false
  385. }
  386. func validateAndSetValue(kind reflect.Kind, value reflect.Value, str string, opts *fieldOptionsWithContext) error {
  387. if !value.CanSet() {
  388. return errValueNotSettable
  389. }
  390. v, err := convertType(kind, str)
  391. if err != nil {
  392. return err
  393. }
  394. if err := validateValueRange(v, opts); err != nil {
  395. return err
  396. }
  397. return setMatchedPrimitiveValue(kind, value, v)
  398. }
  399. func validateJsonNumberRange(v json.Number, opts *fieldOptionsWithContext) error {
  400. if opts == nil || opts.Range == nil {
  401. return nil
  402. }
  403. fv, err := v.Float64()
  404. if err != nil {
  405. return err
  406. }
  407. return validateNumberRange(fv, opts.Range)
  408. }
  409. func validateNumberRange(fv float64, nr *numberRange) error {
  410. if nr == nil {
  411. return nil
  412. }
  413. if (nr.leftInclude && fv < nr.left) || (!nr.leftInclude && fv <= nr.left) {
  414. return errNumberRange
  415. }
  416. if (nr.rightInclude && fv > nr.right) || (!nr.rightInclude && fv >= nr.right) {
  417. return errNumberRange
  418. }
  419. return nil
  420. }
  421. func validateValueInOptions(options []string, value interface{}) error {
  422. if len(options) > 0 {
  423. switch v := value.(type) {
  424. case string:
  425. if !stringx.Contains(options, v) {
  426. return fmt.Errorf(`error: value "%s" is not defined in options "%v"`, v, options)
  427. }
  428. default:
  429. if !stringx.Contains(options, Repr(v)) {
  430. return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, value, options)
  431. }
  432. }
  433. }
  434. return nil
  435. }
  436. func validateValueRange(mapValue interface{}, opts *fieldOptionsWithContext) error {
  437. if opts == nil || opts.Range == nil {
  438. return nil
  439. }
  440. fv, ok := toFloat64(mapValue)
  441. if !ok {
  442. return errNumberRange
  443. }
  444. return validateNumberRange(fv, opts.Range)
  445. }