hook.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package map2struct
  2. import (
  3. "github.com/mitchellh/mapstructure"
  4. "github.com/shopspring/decimal"
  5. "github.com/spf13/cast"
  6. "gopkg.in/guregu/null.v4"
  7. "reflect"
  8. "time"
  9. )
  10. var timeLocation *time.Location
  11. func init() {
  12. timeLocation, _ = time.LoadLocation("Asia/Shanghai")
  13. }
  14. func ToTimeHookFunc() mapstructure.DecodeHookFunc {
  15. return func(
  16. f reflect.Type,
  17. t reflect.Type,
  18. data interface{}) (interface{}, error) {
  19. if t != reflect.TypeOf(time.Time{}) {
  20. return data, nil
  21. }
  22. switch f.Kind() {
  23. case reflect.String:
  24. return cast.ToTimeInDefaultLocationE(data, timeLocation)
  25. case reflect.Float64:
  26. return time.Unix(0, int64(data.(float64))*int64(time.Millisecond)), nil
  27. case reflect.Int64:
  28. return time.Unix(0, data.(int64)*int64(time.Millisecond)), nil
  29. default:
  30. return data, nil
  31. }
  32. // Convert it by parsing
  33. }
  34. }
  35. func ToDecimalHookFunc() mapstructure.DecodeHookFunc {
  36. return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
  37. if t == reflect.TypeOf(decimal.Decimal{}) {
  38. if f.Kind() == reflect.Float64 {
  39. return decimal.NewFromFloat(data.(float64)), nil
  40. }
  41. if input := data.(string); input != "" {
  42. return decimal.NewFromString(data.(string))
  43. }
  44. return decimal.Decimal{}, nil
  45. }
  46. return data, nil
  47. }
  48. }
  49. func ToNullableStringHookFunc() mapstructure.DecodeHookFunc {
  50. return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
  51. if t == reflect.TypeOf(null.String{}) {
  52. return null.StringFrom(data.(string)), nil
  53. }
  54. return data, nil
  55. }
  56. }