utils.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha256"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "math/rand"
  11. "net"
  12. "os"
  13. "reflect"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "unicode"
  19. )
  20. var (
  21. DB_QUERY_WHERE_EMPTY = errors.New("where is empty")
  22. DB_RECORD_NOT_EXISTS = errors.New("record is not exists")
  23. DB_DUPLICATE = errors.New("database duplicate")
  24. )
  25. func GetUniqueLogID(cmd string) string {
  26. return fmt.Sprintf("%d_%s", time.Now().Unix(), cmd)
  27. }
  28. // 获取偏移天数的某天的某个时刻的时间戳
  29. func GetTimestampInOffsetDay(offsetDay, hour, min, sec int) int64 {
  30. nowTime := time.Now()
  31. todayZeroTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local)
  32. offsetDayZeroTime := todayZeroTime.AddDate(0, 0, offsetDay)
  33. return offsetDayZeroTime.Unix() + int64(hour*3600+min*60+sec)
  34. }
  35. func BeToday(ts int64) bool {
  36. theTime := time.Unix(ts, 0)
  37. nowTime := time.Now()
  38. // 年、月、日都相同,则是同一天
  39. return (theTime.Year() == nowTime.Year() && theTime.Month() == nowTime.Month() && theTime.Day() == nowTime.Day())
  40. }
  41. // 获取某个时间戳的0点时间戳、24点时间戳、日期
  42. func Get0_24TimestampAndDate(ts int64) (ts0, ts24 int64, date string) {
  43. theTime := time.Unix(ts, 0)
  44. theZeroTime := time.Date(theTime.Year(), theTime.Month(), theTime.Day(), 0, 0, 0, 0, time.Local)
  45. ts0 = theZeroTime.Unix() // 0点时间戳
  46. ts24 = theZeroTime.AddDate(0, 0, 1).Unix() // 24点时间戳
  47. date = theZeroTime.Format("2006-01-02") // 日期
  48. return
  49. }
  50. // 获取args对应的json字符串
  51. func MarshalJsonString(args ...interface{}) (result string) {
  52. if len(args) > 0 {
  53. if r, err := json.Marshal(args); err == nil {
  54. result = string(r)
  55. }
  56. }
  57. return
  58. }
  59. func GetStructNotZeroField(arg interface{}) []string {
  60. v := reflect.ValueOf(arg)
  61. if v.Kind() == reflect.Ptr {
  62. v = v.Elem()
  63. }
  64. result := make([]string, 0)
  65. if v.Kind() == reflect.Struct {
  66. numField := v.NumField()
  67. for i := 0; i < numField; i++ {
  68. if !reflect.DeepEqual(v.Field(i).Interface(), reflect.Zero(v.Field(i).Type()).Interface()) {
  69. result = append(result, v.Type().Field(i).Name)
  70. }
  71. }
  72. }
  73. return result
  74. }
  75. // 生成订单号
  76. func GenOrderNO(orderType int) string {
  77. nowTime := time.Now()
  78. nowDate := nowTime.Format("20060102")
  79. ym := string([]byte(nowDate)[3:6])
  80. d := string([]byte(nowDate)[6:])
  81. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  82. return fmt.Sprintf("%d%s%d%s%05d", orderType, ym, r.Intn(10), d, r.Intn(10000))
  83. }
  84. func GetRuneSubstring(src string, start, length int) string {
  85. rs := []rune(src)
  86. rl := len(rs)
  87. end := 0
  88. if start < 0 {
  89. start = rl - 1 + start
  90. }
  91. end = start + length
  92. if start > end {
  93. start, end = end, start
  94. }
  95. if start < 0 {
  96. start = 0
  97. }
  98. if start > rl {
  99. start = rl
  100. }
  101. if end < 0 {
  102. end = 0
  103. }
  104. if end > rl {
  105. end = rl
  106. }
  107. return string(rs[start:end])
  108. }
  109. func MD5(text string) string {
  110. h := md5.New()
  111. h.Write([]byte(text))
  112. return hex.EncodeToString(h.Sum(nil))
  113. }
  114. func SHA256(text string) string {
  115. h := sha256.New()
  116. h.Write([]byte(text))
  117. return hex.EncodeToString(h.Sum(nil))
  118. }
  119. func GetEnv(name string) string {
  120. value := os.Getenv(name)
  121. if value == "" {
  122. fmt.Printf(`hasn't %s env var\n`, name)
  123. os.Exit(1)
  124. }
  125. return value
  126. }
  127. func Base64URLDecode(data string) ([]byte, error) {
  128. var missing = (4 - len(data)%4) % 4
  129. data += strings.Repeat("=", missing)
  130. return base64.URLEncoding.DecodeString(data)
  131. }
  132. func Base64UrlSafeEncode(source []byte) string {
  133. // Base64 Url Safe is the same as Base64 but does not contain '/' and '+' (replaced by '_' and '-') and trailing '=' are removed.
  134. bytearr := base64.StdEncoding.EncodeToString(source)
  135. safeurl := strings.Replace(string(bytearr), "/", "_", -1)
  136. safeurl = strings.Replace(safeurl, "+", "-", -1)
  137. safeurl = strings.Replace(safeurl, "=", "", -1)
  138. return safeurl
  139. }
  140. //生成reportId 唯一标识
  141. func GenReportID(module string) string {
  142. macAddr := ""
  143. for _, addr := range macAddrs() {
  144. macAddr += addr
  145. }
  146. if macAddr == "" {
  147. macAddr = RandomString(10)
  148. }
  149. reportId := macAddr + module + strconv.FormatInt(time.Now().UnixNano(), 10)
  150. return MD5(reportId)
  151. }
  152. func macAddrs() (macAddrs []string) {
  153. netInterfaces, err := net.Interfaces()
  154. if err != nil {
  155. return macAddrs
  156. }
  157. for _, netInterface := range netInterfaces {
  158. macAddr := netInterface.HardwareAddr.String()
  159. if len(macAddr) == 0 {
  160. continue
  161. }
  162. macAddrs = append(macAddrs, macAddr)
  163. }
  164. return macAddrs
  165. }
  166. //根据length获取随机字符串
  167. func RandomString(length int) string {
  168. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  169. bytes := []byte(str)
  170. result := []byte{}
  171. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  172. for i := 0; i < length; i++ {
  173. result = append(result, bytes[r.Intn(len(bytes))])
  174. }
  175. return string(result)
  176. }
  177. func ParsePlate(plate string) (string, string) {
  178. var index int
  179. for i, r := range plate {
  180. if !unicode.Is(unicode.Scripts["Han"], r) {
  181. index = i
  182. break
  183. }
  184. }
  185. sf := plate[0:index]
  186. hphm := plate[index:]
  187. return sf, hphm
  188. }
  189. func MobileVerify(number string) bool {
  190. regular := `^1([38][0-9]|14[57]|5[^4])\d{8}$`
  191. reg := regexp.MustCompile(regular)
  192. return reg.MatchString(number)
  193. }
  194. func CheckPlate(plate string, plateType string) (string, error) {
  195. var index int
  196. plate = strings.Replace(plate, " ", "", -1)
  197. for i, r := range plate {
  198. if !unicode.Is(unicode.Scripts["Han"], r) {
  199. index = i
  200. break
  201. }
  202. }
  203. if index != 3 {
  204. return "", errors.New("车牌格式错误")
  205. }
  206. if len(plate[index:]) != 6 && len(plate[index:]) != 7 {
  207. return "", errors.New("车牌格式错误")
  208. }
  209. if len((plate[index:])) == 7 {
  210. if plateType != "51" && plateType != "52" && plateType != "" {
  211. return "", errors.New("车牌格式错误")
  212. }
  213. }
  214. return plate, nil
  215. }
  216. func CheckVin(vin string) (string, error) {
  217. vin = strings.Replace(vin, " ", "", -1)
  218. if len(vin) != 17 {
  219. return "", errors.New("vin码格式错误")
  220. }
  221. return vin, nil
  222. }