utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. if intValue, err := strconv.ParseInt(str, 10, 64); err != nil {
  113. return 0, fmt.Errorf("the value %q cannot parsed as int", str)
  114. } else {
  115. return intValue, nil
  116. }
  117. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  118. if uintValue, err := strconv.ParseUint(str, 10, 64); err != nil {
  119. return 0, fmt.Errorf("the value %q cannot parsed as uint", str)
  120. } else {
  121. return uintValue, nil
  122. }
  123. case reflect.Float32, reflect.Float64:
  124. if floatValue, err := strconv.ParseFloat(str, 64); err != nil {
  125. return 0, fmt.Errorf("the value %q cannot parsed as float", str)
  126. } else {
  127. return floatValue, nil
  128. }
  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. } else {
  166. fieldOpts.Options = strings.Split(segs[1], optionSeparator)
  167. }
  168. case strings.HasPrefix(option, defaultOption):
  169. segs := strings.Split(option, equalToken)
  170. if len(segs) != 2 {
  171. return "", nil, fmt.Errorf("field %s has wrong default option", field.Name)
  172. } else {
  173. fieldOpts.Default = strings.TrimSpace(segs[1])
  174. }
  175. case strings.HasPrefix(option, rangeOption):
  176. segs := strings.Split(option, equalToken)
  177. if len(segs) != 2 {
  178. return "", nil, fmt.Errorf("field %s has wrong range", field.Name)
  179. }
  180. if nr, err := parseNumberRange(segs[1]); err != nil {
  181. return "", nil, err
  182. } else {
  183. fieldOpts.Range = nr
  184. }
  185. }
  186. }
  187. return key, &fieldOpts, nil
  188. }
  189. func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {
  190. numFields := tp.NumField()
  191. for i := 0; i < numFields; i++ {
  192. childField := tp.Field(i)
  193. if usingDifferentKeys(tag, childField) {
  194. return true, nil
  195. }
  196. _, opts, err := parseKeyAndOptions(tag, childField)
  197. if err != nil {
  198. return false, err
  199. }
  200. if opts == nil {
  201. if childField.Type.Kind() != reflect.Struct {
  202. return true, nil
  203. }
  204. if required, err := implicitValueRequiredStruct(tag, childField.Type); err != nil {
  205. return false, err
  206. } else if required {
  207. return true, nil
  208. }
  209. } else if !opts.Optional && len(opts.Default) == 0 {
  210. return true, nil
  211. } else if len(opts.OptionalDep) > 0 && opts.OptionalDep[0] == notSymbol {
  212. return true, nil
  213. }
  214. }
  215. return false, nil
  216. }
  217. func maybeNewValue(field reflect.StructField, value reflect.Value) {
  218. if field.Type.Kind() == reflect.Ptr && value.IsNil() {
  219. value.Set(reflect.New(value.Type().Elem()))
  220. }
  221. }
  222. // don't modify returned fieldOptions, it's cached and shared among different calls.
  223. func parseKeyAndOptions(tagName string, field reflect.StructField) (string, *fieldOptions, error) {
  224. value := field.Tag.Get(tagName)
  225. if len(value) == 0 {
  226. return field.Name, nil, nil
  227. }
  228. cacheLock.RLock()
  229. cache, ok := optionsCache[value]
  230. cacheLock.RUnlock()
  231. if ok {
  232. return stringx.TakeOne(cache.key, field.Name), cache.options, cache.err
  233. }
  234. key, options, err := doParseKeyAndOptions(field, value)
  235. cacheLock.Lock()
  236. optionsCache[value] = optionsCacheValue{
  237. key: key,
  238. options: options,
  239. err: err,
  240. }
  241. cacheLock.Unlock()
  242. return stringx.TakeOne(key, field.Name), options, err
  243. }
  244. // support below notations:
  245. // [:5] (:5] [:5) (:5)
  246. // [1:] [1:) (1:] (1:)
  247. // [1:5] [1:5) (1:5] (1:5)
  248. func parseNumberRange(str string) (*numberRange, error) {
  249. if len(str) == 0 {
  250. return nil, errNumberRange
  251. }
  252. var leftInclude bool
  253. switch str[0] {
  254. case '[':
  255. leftInclude = true
  256. case '(':
  257. leftInclude = false
  258. default:
  259. return nil, errNumberRange
  260. }
  261. str = str[1:]
  262. if len(str) == 0 {
  263. return nil, errNumberRange
  264. }
  265. var rightInclude bool
  266. switch str[len(str)-1] {
  267. case ']':
  268. rightInclude = true
  269. case ')':
  270. rightInclude = false
  271. default:
  272. return nil, errNumberRange
  273. }
  274. str = str[:len(str)-1]
  275. fields := strings.Split(str, ":")
  276. if len(fields) != 2 {
  277. return nil, errNumberRange
  278. }
  279. if len(fields[0]) == 0 && len(fields[1]) == 0 {
  280. return nil, errNumberRange
  281. }
  282. var left float64
  283. if len(fields[0]) > 0 {
  284. var err error
  285. if left, err = strconv.ParseFloat(fields[0], 64); err != nil {
  286. return nil, err
  287. }
  288. } else {
  289. left = -math.MaxFloat64
  290. }
  291. var right float64
  292. if len(fields[1]) > 0 {
  293. var err error
  294. if right, err = strconv.ParseFloat(fields[1], 64); err != nil {
  295. return nil, err
  296. }
  297. } else {
  298. right = math.MaxFloat64
  299. }
  300. return &numberRange{
  301. left: left,
  302. leftInclude: leftInclude,
  303. right: right,
  304. rightInclude: rightInclude,
  305. }, nil
  306. }
  307. func setMatchedPrimitiveValue(kind reflect.Kind, value reflect.Value, v interface{}) error {
  308. switch kind {
  309. case reflect.Bool:
  310. value.SetBool(v.(bool))
  311. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  312. value.SetInt(v.(int64))
  313. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  314. value.SetUint(v.(uint64))
  315. case reflect.Float32, reflect.Float64:
  316. value.SetFloat(v.(float64))
  317. case reflect.String:
  318. value.SetString(v.(string))
  319. default:
  320. return errUnsupportedType
  321. }
  322. return nil
  323. }
  324. func setValue(kind reflect.Kind, value reflect.Value, str string) error {
  325. if !value.CanSet() {
  326. return errValueNotSettable
  327. }
  328. v, err := convertType(kind, str)
  329. if err != nil {
  330. return err
  331. }
  332. return setMatchedPrimitiveValue(kind, value, v)
  333. }
  334. func structValueRequired(tag string, tp reflect.Type) (bool, error) {
  335. structCacheLock.RLock()
  336. val, ok := structRequiredCache[tp]
  337. structCacheLock.RUnlock()
  338. if ok {
  339. return val.required, val.err
  340. }
  341. required, err := implicitValueRequiredStruct(tag, tp)
  342. structCacheLock.Lock()
  343. structRequiredCache[tp] = requiredCacheValue{
  344. required: required,
  345. err: err,
  346. }
  347. structCacheLock.Unlock()
  348. return required, err
  349. }
  350. func toFloat64(v interface{}) (float64, bool) {
  351. switch val := v.(type) {
  352. case int:
  353. return float64(val), true
  354. case int8:
  355. return float64(val), true
  356. case int16:
  357. return float64(val), true
  358. case int32:
  359. return float64(val), true
  360. case int64:
  361. return float64(val), true
  362. case uint:
  363. return float64(val), true
  364. case uint8:
  365. return float64(val), true
  366. case uint16:
  367. return float64(val), true
  368. case uint32:
  369. return float64(val), true
  370. case uint64:
  371. return float64(val), true
  372. case float32:
  373. return float64(val), true
  374. case float64:
  375. return val, true
  376. default:
  377. return 0, false
  378. }
  379. }
  380. func usingDifferentKeys(key string, field reflect.StructField) bool {
  381. if len(field.Tag) > 0 {
  382. if _, ok := field.Tag.Lookup(key); !ok {
  383. return true
  384. }
  385. }
  386. return false
  387. }
  388. func validateAndSetValue(kind reflect.Kind, value reflect.Value, str string, opts *fieldOptionsWithContext) error {
  389. if !value.CanSet() {
  390. return errValueNotSettable
  391. }
  392. v, err := convertType(kind, str)
  393. if err != nil {
  394. return err
  395. }
  396. if err := validateValueRange(v, opts); err != nil {
  397. return err
  398. }
  399. return setMatchedPrimitiveValue(kind, value, v)
  400. }
  401. func validateJsonNumberRange(v json.Number, opts *fieldOptionsWithContext) error {
  402. if opts == nil || opts.Range == nil {
  403. return nil
  404. }
  405. fv, err := v.Float64()
  406. if err != nil {
  407. return err
  408. }
  409. return validateNumberRange(fv, opts.Range)
  410. }
  411. func validateNumberRange(fv float64, nr *numberRange) error {
  412. if nr == nil {
  413. return nil
  414. }
  415. if (nr.leftInclude && fv < nr.left) || (!nr.leftInclude && fv <= nr.left) {
  416. return errNumberRange
  417. }
  418. if (nr.rightInclude && fv > nr.right) || (!nr.rightInclude && fv >= nr.right) {
  419. return errNumberRange
  420. }
  421. return nil
  422. }
  423. func validateValueInOptions(options []string, value interface{}) error {
  424. if len(options) > 0 {
  425. switch v := value.(type) {
  426. case string:
  427. if !stringx.Contains(options, v) {
  428. return fmt.Errorf(`error: value "%s" is not defined in options "%v"`, v, options)
  429. }
  430. default:
  431. if !stringx.Contains(options, Repr(v)) {
  432. return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, value, options)
  433. }
  434. }
  435. }
  436. return nil
  437. }
  438. func validateValueRange(mapValue interface{}, opts *fieldOptionsWithContext) error {
  439. if opts == nil || opts.Range == nil {
  440. return nil
  441. }
  442. fv, ok := toFloat64(mapValue)
  443. if !ok {
  444. return errNumberRange
  445. }
  446. return validateNumberRange(fv, opts.Range)
  447. }