long.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package utils
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. type Long int64
  9. func (t Long) MarshalJSON() ([]byte, error) {
  10. b := fmt.Sprintf(`"%d"`, t)
  11. return []byte(b), nil
  12. }
  13. func (t *Long) UnmarshalJSON(value []byte) error {
  14. var v = strings.TrimSpace(strings.Trim(string(value), "\""))
  15. if v == "" {
  16. *t = Long(0)
  17. return nil
  18. }
  19. num, err := strconv.ParseInt(v, 10, 64)
  20. if err != nil {
  21. return err
  22. }
  23. *t = Long(num)
  24. return nil
  25. }
  26. func (t Long) MarshalText() ([]byte, error) {
  27. return []byte(t.String()), nil
  28. }
  29. func (t *Long) UnmarshalText(data []byte) error {
  30. *t = t.FromString(string(data))
  31. return nil
  32. }
  33. func (t Long) FromString(str string) Long {
  34. num, err := strconv.ParseInt(str, 10, 64)
  35. if nil != err {
  36. return 0
  37. }
  38. return Long(num)
  39. }
  40. func (t Long) String() string {
  41. return strconv.FormatInt(int64(t), 10)
  42. }
  43. func (t Long) Value() (driver.Value, error) {
  44. if t.IsZero() {
  45. return int64(0), nil
  46. }
  47. return int64(t), nil
  48. }
  49. func (t *Long) Scan(value interface{}) error {
  50. if value == nil {
  51. return nil
  52. }
  53. if v, ok := value.(int64); ok {
  54. *t = Long(v)
  55. } else if v, ok := value.([]uint8); ok {
  56. num, err := strconv.ParseInt(string(v), 10, 64)
  57. if err == nil {
  58. *t = Long(num)
  59. }
  60. }
  61. return nil
  62. }
  63. func (t Long) IsZero() bool {
  64. return t == 0
  65. }