utils.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. "strconv"
  15. "strings"
  16. "time"
  17. "gd_vehicle/apis"
  18. "gd_vehicle/common.in/cache"
  19. "gd_vehicle/consts"
  20. "github.com/json-iterator/go"
  21. )
  22. var (
  23. DB_QUERY_WHERE_EMPTY = errors.New("where is empty")
  24. DB_RECORD_NOT_EXISTS = errors.New("record is not exists")
  25. DB_DUPLICATE = errors.New("database duplicate")
  26. )
  27. var (
  28. idCertMatrix = []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
  29. idCertVerifyCode = []byte("10X98765432")
  30. socialCreditMatrix = []int{1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28}
  31. socialCreditMap = map[int]int{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
  32. 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'J': 18,
  33. 'K': 19, 'L': 20, 'M': 21, 'N': 22, 'P': 23, 'Q': 24, 'R': 25, 'T': 26, 'U': 27,
  34. 'W': 28, 'X': 29, 'Y': 30}
  35. socialCreditMapKeys = []int{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'W', 'X', 'Y'}
  36. socialCreditMapValues = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}
  37. )
  38. const DAYSECOND = 24 * 60 * 60
  39. const MINUTESECOND = 60
  40. func GetUniqueLogID(cmd string) string {
  41. return fmt.Sprintf("%d_%s", time.Now().Unix(), cmd)
  42. }
  43. // 获取偏移天数的某天的某个时刻的时间戳
  44. func GetTimestampInOffsetDay(offsetDay, hour, min, sec int) int64 {
  45. nowTime := time.Now()
  46. todayZeroTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local)
  47. offsetDayZeroTime := todayZeroTime.AddDate(0, 0, offsetDay)
  48. return offsetDayZeroTime.Unix() + int64(hour*3600+min*60+sec)
  49. }
  50. func BeToday(ts int64) bool {
  51. theTime := time.Unix(ts, 0)
  52. nowTime := time.Now()
  53. // 年、月、日都相同,则是同一天
  54. return (theTime.Year() == nowTime.Year() && theTime.Month() == nowTime.Month() && theTime.Day() == nowTime.Day())
  55. }
  56. // 获取某个时间戳的0点时间戳、24点时间戳、日期
  57. func Get0_24TimestampAndDate(ts int64) (ts0, ts24 int64, date string) {
  58. theTime := time.Unix(ts, 0)
  59. theZeroTime := time.Date(theTime.Year(), theTime.Month(), theTime.Day(), 0, 0, 0, 0, time.Local)
  60. ts0 = theZeroTime.Unix() // 0点时间戳
  61. ts24 = theZeroTime.AddDate(0, 0, 1).Unix() // 24点时间戳
  62. date = theZeroTime.Format("2006-01-02") // 日期
  63. return
  64. }
  65. // 获取args对应的json字符串
  66. func MarshalJsonString(args ...interface{}) (result string) {
  67. if len(args) > 0 {
  68. if r, err := json.Marshal(args); err == nil {
  69. result = string(r)
  70. }
  71. }
  72. return
  73. }
  74. func GetStructNotZeroField(arg interface{}) []string {
  75. v := reflect.ValueOf(arg)
  76. if v.Kind() == reflect.Ptr {
  77. v = v.Elem()
  78. }
  79. result := make([]string, 0)
  80. if v.Kind() == reflect.Struct {
  81. numField := v.NumField()
  82. for i := 0; i < numField; i++ {
  83. if !reflect.DeepEqual(v.Field(i).Interface(), reflect.Zero(v.Field(i).Type()).Interface()) {
  84. result = append(result, v.Type().Field(i).Name)
  85. }
  86. }
  87. }
  88. return result
  89. }
  90. // 生成订单号
  91. func GenOrderNO(orderType int) string {
  92. nowTime := time.Now()
  93. nowDate := nowTime.Format("20060102")
  94. ym := string([]byte(nowDate)[3:6])
  95. d := string([]byte(nowDate)[6:])
  96. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  97. return fmt.Sprintf("%d%s%d%s%05d", orderType, ym, r.Intn(10), d, r.Intn(10000))
  98. }
  99. func GetRuneSubstring(src string, start, length int) string {
  100. rs := []rune(src)
  101. rl := len(rs)
  102. end := 0
  103. if start < 0 {
  104. start = rl - 1 + start
  105. }
  106. end = start + length
  107. if start > end {
  108. start, end = end, start
  109. }
  110. if start < 0 {
  111. start = 0
  112. }
  113. if start > rl {
  114. start = rl
  115. }
  116. if end < 0 {
  117. end = 0
  118. }
  119. if end > rl {
  120. end = rl
  121. }
  122. return string(rs[start:end])
  123. }
  124. func MD5(text string) string {
  125. h := md5.New()
  126. h.Write([]byte(text))
  127. return hex.EncodeToString(h.Sum(nil))
  128. }
  129. func SHA256(text string) string {
  130. h := sha256.New()
  131. h.Write([]byte(text))
  132. return hex.EncodeToString(h.Sum(nil))
  133. }
  134. func GetEnv(name string) string {
  135. value := os.Getenv(name)
  136. if value == "" {
  137. fmt.Printf(`hasn't %s env var\n`, name)
  138. os.Exit(1)
  139. }
  140. return value
  141. }
  142. func Base64URLDecode(data string) ([]byte, error) {
  143. var missing = (4 - len(data)%4) % 4
  144. data += strings.Repeat("=", missing)
  145. return base64.URLEncoding.DecodeString(data)
  146. }
  147. func Base64UrlSafeEncode(source []byte) string {
  148. // Base64 Url Safe is the same as Base64 but does not contain '/' and '+' (replaced by '_' and '-') and trailing '=' are removed.
  149. bytearr := base64.StdEncoding.EncodeToString(source)
  150. safeurl := strings.Replace(string(bytearr), "/", "_", -1)
  151. safeurl = strings.Replace(safeurl, "+", "-", -1)
  152. safeurl = strings.Replace(safeurl, "=", "", -1)
  153. return safeurl
  154. }
  155. //生成reportId 唯一标识
  156. func GenReportID(module string) string {
  157. macAddr := ""
  158. for _, addr := range macAddrs() {
  159. macAddr += addr
  160. }
  161. if macAddr == "" {
  162. macAddr = RandomString(10)
  163. }
  164. reportId := macAddr + module + strconv.FormatInt(time.Now().UnixNano(), 10)
  165. return MD5(reportId)
  166. }
  167. func macAddrs() (macAddrs []string) {
  168. netInterfaces, err := net.Interfaces()
  169. if err != nil {
  170. return macAddrs
  171. }
  172. for _, netInterface := range netInterfaces {
  173. macAddr := netInterface.HardwareAddr.String()
  174. if len(macAddr) == 0 {
  175. continue
  176. }
  177. macAddrs = append(macAddrs, macAddr)
  178. }
  179. return macAddrs
  180. }
  181. //根据length获取随机字符串
  182. func RandomString(length int) string {
  183. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  184. bytes := []byte(str)
  185. result := []byte{}
  186. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  187. for i := 0; i < length; i++ {
  188. result = append(result, bytes[r.Intn(len(bytes))])
  189. }
  190. return string(result)
  191. }
  192. //身份证
  193. func CheckIDCert(str string) (res bool) {
  194. defer func() {
  195. if r := recover(); r != nil {
  196. res = false
  197. }
  198. }()
  199. idCert := strings.ToUpper(str)
  200. if len(idCert) != 18 {
  201. return false
  202. }
  203. year, err := strconv.Atoi(idCert[6:10])
  204. if err != nil {
  205. return false
  206. }
  207. if !(1900 < year && year < 2100) {
  208. return false
  209. }
  210. check := 0
  211. lastLetter := 0
  212. for index, value := range []byte(idCert) {
  213. if index == 17 {
  214. lastLetter = int(value)
  215. break
  216. }
  217. if !(value >= 48 && value <= 57) {
  218. return false
  219. }
  220. v := value - 48
  221. check = check + idCertMatrix[index]*int(v)
  222. }
  223. if !((lastLetter >= 48 && lastLetter <= 57) || lastLetter == 'X') {
  224. return false
  225. }
  226. timeLayout := "20060102" //转化所需模板
  227. loc, _ := time.LoadLocation("Local") //重要:获取时区
  228. _, err = time.ParseInLocation(timeLayout, idCert[6:14], loc) //使用模板在对应时区转化为time.time类型
  229. if err != nil {
  230. return false
  231. }
  232. verifyCode := int(idCertVerifyCode[check%11])
  233. if lastLetter == verifyCode {
  234. return true
  235. }
  236. return false
  237. }
  238. func IsReuseTime(reuseTime int64, timestamp int64) bool {
  239. if timestamp == 0 {
  240. return false
  241. }
  242. reuseSencod := reuseTime * DAYSECOND
  243. t := time.Unix(timestamp, 0)
  244. now := time.Now()
  245. // 60s短时复用
  246. if reuseTime == 0 {
  247. if now.Unix()-timestamp > MINUTESECOND {
  248. return false
  249. }
  250. return true
  251. }
  252. start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).Unix()
  253. end := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
  254. if end-start >= reuseSencod {
  255. return false
  256. }
  257. return true
  258. }
  259. // 时间字符串转化成时间戳
  260. func TimeStringToTs(s string) int64 {
  261. if strings.Count(s, "-") == 1 {
  262. s += "-01"
  263. }
  264. location, _ := time.ParseInLocation("2006-01-02", s, time.Local)
  265. return location.Unix()
  266. }
  267. func CheckWorkTime(s string) string {
  268. s = strings.ToUpper(s)
  269. arr := []rune(s)
  270. for _, v := range arr {
  271. if v < 65 || v > 70 {
  272. return "F"
  273. }
  274. }
  275. return s
  276. }
  277. func CheckMile(s string) string {
  278. s = strings.ToUpper(s)
  279. arr := []rune(s)
  280. for _, v := range arr {
  281. if v < 65 || v > 76 {
  282. return "L"
  283. }
  284. }
  285. return s
  286. }
  287. func CheckMileSixMonth(s string) string {
  288. s = strings.ToUpper(s)
  289. arr := []rune(s)
  290. for _, v := range arr {
  291. if v < 65 || v > 73 {
  292. return "I"
  293. }
  294. }
  295. return s
  296. }
  297. func ConvertPlateType(s string) (plateColor string, exist bool) {
  298. plateColorMap := map[string]string{
  299. "01": "1",
  300. "02": "0",
  301. "51": "5",
  302. "52": "4",
  303. }
  304. if v, ok := plateColorMap[s]; ok {
  305. return v, true
  306. }
  307. return
  308. }
  309. func GetDataByRedis(redisKey string, reuseTime int64, reply interface{}, fn func(data string, dest interface{}) error) (bool, error) {
  310. res, err := cache.Redis.Get(redisKey)
  311. if err == nil && res != "" {
  312. rawData := apis.RawData{}
  313. _ = jsoniter.UnmarshalFromString(res, &rawData)
  314. if IsReuseTime(reuseTime, rawData.Timestamp) {
  315. return true, fn(rawData.Data, reply)
  316. }
  317. }
  318. return false, nil
  319. }
  320. func StoreDataToRedis(redisKey, data string) {
  321. store := apis.RawData{
  322. Data: data,
  323. Timestamp: time.Now().Unix(),
  324. }
  325. str, _ := jsoniter.MarshalToString(store)
  326. _, _ = cache.Redis.SetEx(redisKey, consts.RedisDataExipred, str)
  327. return
  328. }