utils.go 12 KB

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