util.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package client
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func ToStrings(data interface{}) []string {
  7. var i []string
  8. if v, ok := data.([]interface{}); ok {
  9. for _, in := range v {
  10. i = append(i, fmt.Sprint(in))
  11. }
  12. }
  13. return i
  14. }
  15. func ToString(data interface{}) string {
  16. if data == nil {
  17. return ""
  18. }
  19. return fmt.Sprint(data)
  20. }
  21. func ToFloat64(data interface{}) float64 {
  22. if v, ok := data.(float64); ok {
  23. return v
  24. }
  25. if v, ok := data.(int64); ok {
  26. return float64(v)
  27. }
  28. return 0
  29. }
  30. func ToFloat32(data interface{}) float32 {
  31. if v, ok := data.(float32); ok {
  32. return v
  33. }
  34. if v, ok := data.(float64); ok {
  35. return float32(v)
  36. }
  37. if v, ok := data.(int64); ok {
  38. return float32(v)
  39. }
  40. return 0
  41. }
  42. func ToInt(data interface{}) int {
  43. if v, ok := data.(int); ok {
  44. return v
  45. }
  46. if v, ok := data.(int64); ok {
  47. return int(v)
  48. }
  49. if v, ok := data.(float64); ok {
  50. return int(v)
  51. }
  52. if v, ok := data.(float32); ok {
  53. return int(v)
  54. }
  55. return 0
  56. }
  57. func ToBool(data interface{}) bool {
  58. if v, ok := data.(bool); ok {
  59. return v
  60. }
  61. return ToInt(data) == 1
  62. }
  63. const (
  64. GRPC_DATETIME_FROM_SQL_FORMAT = "2006-01-02T15:04:05.999999999-07:00"
  65. GRPC_DATETIME_FROM_SQL_FORMAT2 = "2006-01-02T15:04:05.999999999Z"
  66. DATETIME_FROM_ISO_FORMAT = "2006-01-02T15:04:05.999-07:00"
  67. )
  68. func ToTime(data interface{}) (*time.Time, error) {
  69. if v, ok := data.(time.Time); ok {
  70. return &v, nil
  71. }
  72. str := ToString(data)
  73. dateTime, err := time.Parse(GRPC_DATETIME_FROM_SQL_FORMAT, str)
  74. if err != nil {
  75. dateTime, err = time.Parse(GRPC_DATETIME_FROM_SQL_FORMAT2, str)
  76. if err != nil {
  77. return nil, err
  78. }
  79. }
  80. return &dateTime, nil
  81. }
  82. func ToTimeFromISO(data interface{}) (*time.Time, error) {
  83. str := ToString(data)
  84. dateTime, err := time.Parse(DATETIME_FROM_ISO_FORMAT, str)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return &dateTime, nil
  89. }