utils.go 6.2 KB

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