common.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package utils
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "fmt"
  9. "math"
  10. "math/rand"
  11. "regexp"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. // 手机号,电子邮箱正则
  18. const (
  19. RegularMobile = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9])|(17[0-9])|(16[0-9])|(19[0-9]))\\d{8}$" //手机号码
  20. RegularEmail = `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
  21. )
  22. const TelAreaCodeHome = "86" // 大陆区号
  23. // 数据没有记录
  24. func ErrNoRow() string {
  25. return "<QuerySeter> no row found"
  26. }
  27. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  28. // ValidateMobileFormatat 校验手机格式
  29. func ValidateMobileFormatat(mobileNum string) bool {
  30. reg := regexp.MustCompile(RegularMobile)
  31. return reg.MatchString(mobileNum)
  32. }
  33. // ValidateEmailFormatat 校验邮箱格式
  34. func ValidateEmailFormatat(email string) bool {
  35. reg := regexp.MustCompile(RegularEmail)
  36. return reg.MatchString(email)
  37. }
  38. func MD5(data string) string {
  39. m := md5.Sum([]byte(data))
  40. return hex.EncodeToString(m[:])
  41. }
  42. func CheckPwd(pwd string) bool {
  43. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  44. reg := regexp.MustCompile(compile)
  45. flag := reg.MatchString(pwd)
  46. return flag
  47. }
  48. // 计算分页起始页
  49. func StartIndex(page, pagesize int) int {
  50. if page > 1 {
  51. return (page - 1) * pagesize
  52. }
  53. return 0
  54. }
  55. // GetLikeKeywordPars 获取sql查询中的参数切片
  56. func GetLikeKeywordPars(pars []interface{}, keyword string, num int) (newPars []interface{}) {
  57. newPars = pars
  58. if newPars == nil {
  59. newPars = make([]interface{}, 0)
  60. }
  61. for i := 1; i <= num; i++ {
  62. newPars = append(newPars, `%`+keyword+`%`)
  63. }
  64. return
  65. }
  66. // GetRandDigit 获取数字随机字符
  67. func GetRandDigit(n int) string {
  68. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  69. }
  70. func GetRandString(size int) string {
  71. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  72. randomSb := ""
  73. digitSize := len(allLetterDigit)
  74. for i := 0; i < size; i++ {
  75. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  76. }
  77. return randomSb
  78. }
  79. // HmacSha256 计算HmacSha256
  80. // key 是加密所使用的key
  81. // data 是加密的内容
  82. func HmacSha256(key string, data string) []byte {
  83. mac := hmac.New(sha256.New, []byte(key))
  84. _, _ = mac.Write([]byte(data))
  85. return mac.Sum(nil)
  86. }
  87. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  88. func HmacSha256ToBase64(key string, data string) string {
  89. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  90. }
  91. func GetSign(nonce, timestamp, appId, secret string) (sign string) {
  92. signStrMap := map[string]string{
  93. "nonce": nonce,
  94. "timestamp": timestamp,
  95. "appid": appId,
  96. }
  97. keys := make([]string, 0, len(signStrMap))
  98. for k := range signStrMap {
  99. keys = append(keys, k)
  100. }
  101. sort.Strings(keys)
  102. var signStr string
  103. for _, k := range keys {
  104. signStr += k + "=" + signStrMap[k] + "&"
  105. }
  106. signStr = strings.Trim(signStr, "&")
  107. fmt.Println("signStr:" + signStr)
  108. sign = HmacSha256ToBase64(secret, signStr)
  109. return
  110. }
  111. func GetRandStringNoSpecialChar(size int) string {
  112. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  113. randomSb := ""
  114. digitSize := len(allLetterDigit)
  115. for i := 0; i < size; i++ {
  116. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  117. }
  118. return randomSb
  119. }
  120. func StringsToJSON(str string) string {
  121. rs := []rune(str)
  122. jsons := ""
  123. for _, r := range rs {
  124. rint := int(r)
  125. if rint < 128 {
  126. jsons += string(r)
  127. } else {
  128. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  129. }
  130. }
  131. return jsons
  132. }
  133. func SecondsToHMS(seconds int64) string {
  134. duration := time.Duration(seconds) * time.Second
  135. hours := int64(duration.Hours())
  136. minutes := int64(duration.Minutes()) % 60
  137. secs := int64(duration.Seconds()) % 60
  138. var result string
  139. if hours > 0 {
  140. result += fmt.Sprintf("%d时", hours)
  141. }
  142. if minutes > 0 || (hours > 0 && secs > 0) {
  143. result += fmt.Sprintf("%d分", minutes)
  144. }
  145. if secs > 0 || (hours == 0 && minutes == 0) {
  146. result += fmt.Sprintf("%d秒", secs)
  147. }
  148. return result
  149. }
  150. func Unique[T comparable](slice []T) []T {
  151. seen := make(map[T]struct{})
  152. var unique []T
  153. for _, v := range slice {
  154. if _, exists := seen[v]; !exists {
  155. unique = append(unique, v)
  156. seen[v] = struct{}{}
  157. }
  158. }
  159. return unique
  160. }
  161. func GetOrmReplaceHolder(num int) string {
  162. var stringBuffer strings.Builder
  163. for i := 0; i < num; i++ {
  164. stringBuffer.WriteString("?")
  165. if i != num-1 {
  166. stringBuffer.WriteString(",")
  167. }
  168. }
  169. return stringBuffer.String()
  170. }
  171. func SetKeyExpireToday() time.Duration {
  172. now := time.Now()
  173. endOfDay := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location())
  174. return time.Until(endOfDay)
  175. }