utils.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 r, err := json.Marshal(args); err == nil {
  64. result = string(r)
  65. }
  66. return
  67. }
  68. func GetStructNotZeroField(arg interface{}) []string {
  69. v := reflect.ValueOf(arg)
  70. if v.Kind() == reflect.Ptr {
  71. v = v.Elem()
  72. }
  73. result := make([]string, 0)
  74. if v.Kind() == reflect.Struct {
  75. numField := v.NumField()
  76. for i := 0; i < numField; i++ {
  77. if !reflect.DeepEqual(v.Field(i).Interface(), reflect.Zero(v.Field(i).Type()).Interface()) {
  78. result = append(result, v.Type().Field(i).Name)
  79. }
  80. }
  81. }
  82. return result
  83. }
  84. // 生成订单号
  85. func GenOrderNO(orderType int) string {
  86. nowTime := time.Now()
  87. nowDate := nowTime.Format("20060102")
  88. ym := string([]byte(nowDate)[3:6])
  89. d := string([]byte(nowDate)[6:])
  90. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  91. return fmt.Sprintf("%d%s%d%s%05d", orderType, ym, r.Intn(10), d, r.Intn(10000))
  92. }
  93. func GetRuneSubstring(src string, start, length int) string {
  94. rs := []rune(src)
  95. rl := len(rs)
  96. end := 0
  97. if start < 0 {
  98. start = rl - 1 + start
  99. }
  100. end = start + length
  101. if start > end {
  102. start, end = end, start
  103. }
  104. if start < 0 {
  105. start = 0
  106. }
  107. if start > rl {
  108. start = rl
  109. }
  110. if end < 0 {
  111. end = 0
  112. }
  113. if end > rl {
  114. end = rl
  115. }
  116. return string(rs[start:end])
  117. }
  118. func MD5(text string) string {
  119. h := md5.New()
  120. h.Write([]byte(text))
  121. return hex.EncodeToString(h.Sum(nil))
  122. }
  123. func SHA256(text string) string {
  124. h := sha256.New()
  125. h.Write([]byte(text))
  126. return hex.EncodeToString(h.Sum(nil))
  127. }
  128. func GetEnv(name string) string {
  129. value := os.Getenv(name)
  130. if value == "" {
  131. fmt.Printf(`hasn't %s env var\n`, name)
  132. os.Exit(1)
  133. }
  134. return value
  135. }
  136. func Base64URLDecode(data string) ([]byte, error) {
  137. var missing = (4 - len(data)%4) % 4
  138. data += strings.Repeat("=", missing)
  139. return base64.URLEncoding.DecodeString(data)
  140. }
  141. func Base64UrlSafeEncode(source []byte) string {
  142. // Base64 Url Safe is the same as Base64 but does not contain '/' and '+' (replaced by '_' and '-') and trailing '=' are removed.
  143. bytearr := base64.StdEncoding.EncodeToString(source)
  144. safeurl := strings.Replace(string(bytearr), "/", "_", -1)
  145. safeurl = strings.Replace(safeurl, "+", "-", -1)
  146. safeurl = strings.Replace(safeurl, "=", "", -1)
  147. return safeurl
  148. }
  149. //生成reportId 唯一标识
  150. func GenReportID(module string) string {
  151. macAddr := ""
  152. for _, addr := range macAddrs() {
  153. macAddr += addr
  154. }
  155. if macAddr == "" {
  156. macAddr = RandomString(10)
  157. }
  158. reportId := macAddr + module + strconv.FormatInt(time.Now().UnixNano(), 10)
  159. return MD5(reportId)
  160. }
  161. func macAddrs() (macAddrs []string) {
  162. netInterfaces, err := net.Interfaces()
  163. if err != nil {
  164. return macAddrs
  165. }
  166. for _, netInterface := range netInterfaces {
  167. macAddr := netInterface.HardwareAddr.String()
  168. if len(macAddr) == 0 {
  169. continue
  170. }
  171. macAddrs = append(macAddrs, macAddr)
  172. }
  173. return macAddrs
  174. }
  175. //根据length获取随机字符串
  176. func RandomString(length int) string {
  177. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  178. bytes := []byte(str)
  179. result := []byte{}
  180. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  181. for i := 0; i < length; i++ {
  182. result = append(result, bytes[r.Intn(len(bytes))])
  183. }
  184. return string(result)
  185. }
  186. //身份证
  187. func CheckIDCert(str string) (res bool) {
  188. defer func() {
  189. if r := recover(); r != nil {
  190. res = false
  191. }
  192. }()
  193. idCert := strings.ToUpper(str)
  194. if len(idCert) != 18 {
  195. return false
  196. }
  197. year, err := strconv.Atoi(idCert[6:10])
  198. if err != nil {
  199. return false
  200. }
  201. if !(1900 < year && year < 2100) {
  202. return false
  203. }
  204. check := 0
  205. lastLetter := 0
  206. for index, value := range []byte(idCert) {
  207. if index == 17 {
  208. lastLetter = int(value)
  209. break
  210. }
  211. if !(value >= 48 && value <= 57) {
  212. return false
  213. }
  214. v := value - 48
  215. check = check + idCertMatrix[index]*int(v)
  216. }
  217. if !((lastLetter >= 48 && lastLetter <= 57) || lastLetter == 'X') {
  218. return false
  219. }
  220. timeLayout := "20060102" //转化所需模板
  221. loc, _ := time.LoadLocation("Local") //重要:获取时区
  222. _, err = time.ParseInLocation(timeLayout, idCert[6:14], loc) //使用模板在对应时区转化为time.time类型
  223. if err != nil {
  224. return false
  225. }
  226. verifyCode := int(idCertVerifyCode[check%11])
  227. if lastLetter == verifyCode {
  228. return true
  229. }
  230. return false
  231. }
  232. func IsReuseTime(reuseTime int64, timestamp int64) bool {
  233. if timestamp == 0 {
  234. return false
  235. }
  236. reuseSencod := reuseTime * DAYSECOND
  237. t := time.Unix(timestamp, 0)
  238. now := time.Now()
  239. // 60s短时复用
  240. if reuseTime == 0 {
  241. if now.Unix()-timestamp > MINUTESECOND {
  242. return false
  243. }
  244. return true
  245. }
  246. start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).Unix()
  247. end := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
  248. if end-start >= reuseSencod {
  249. return false
  250. }
  251. return true
  252. }
  253. // 时间字符串转化成时间戳
  254. func TimeStringToTs(s string) int64 {
  255. location, _ := time.ParseInLocation("2006-01-02", s, time.Local)
  256. return location.Unix()
  257. }