utils.go 8.2 KB

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