scrm-go

tools.go 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package utils
  2. import (
  3. "crypto/sha1"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "regexp"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/astaxie/beego"
  15. )
  16. func TimeSub(t1, t2 time.Time) int {
  17. t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
  18. t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)
  19. return int(t1.Sub(t2).Hours() / 24)
  20. }
  21. func MarkBackUrl(backUrl, defaultUrl string) string {
  22. if len(backUrl) == 0 {
  23. backUrl = defaultUrl
  24. } else {
  25. backURLByte, err := base64.URLEncoding.DecodeString(backUrl)
  26. if err != nil {
  27. backUrl = backUrl
  28. } else {
  29. backUrl = string(backURLByte)
  30. }
  31. }
  32. return backUrl
  33. }
  34. func CheckMobile(mobile string) (match bool) {
  35. //过滤手机
  36. match, _ = regexp.MatchString("^1([2358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$", mobile)
  37. return
  38. }
  39. func CheckPhone(phone string) (match bool) {
  40. reg, _ := regexp.MatchString("^0[0-9]{2,3}-?[0-9]{7,8}$", phone)
  41. return reg
  42. }
  43. func CheckHexColor(color string) (match bool) {
  44. reg, _ := regexp.MatchString("^#([0-9a-fA-F]{6})$", color)
  45. return reg
  46. }
  47. func RandCode(min, max int64) string {
  48. if min >= max || min == 0 || max == 0 {
  49. return strconv.FormatInt(max, 10)
  50. }
  51. rand.Seed(time.Now().UnixNano())
  52. randNum := rand.Int63n(max-min) + min
  53. return strconv.FormatInt(randNum, 10)
  54. }
  55. func TimeAgo(timeUnix int64) string {
  56. timeUnixS := time.Unix(timeUnix, 0)
  57. timeNow := time.Now()
  58. timeSub := timeNow.Sub(timeUnixS)
  59. if timeSub < time.Minute*1 {
  60. return "刚刚"
  61. } else if timeSub < time.Hour*1 {
  62. return strconv.Itoa(int(timeSub.Minutes())) + "分钟前"
  63. } else if timeSub < time.Hour*24 {
  64. return strconv.Itoa(int(timeSub.Hours())) + "小时前"
  65. } else if timeSub < time.Hour*24*7 {
  66. return strconv.Itoa(int(timeSub.Hours()/24)) + "天前"
  67. } else {
  68. return timeUnixS.Format("2006-01-02 15:04")
  69. }
  70. return ""
  71. }
  72. //Signature sha1签名
  73. func Signature(params ...string) string {
  74. sort.Strings(params)
  75. h := sha1.New()
  76. for _, s := range params {
  77. io.WriteString(h, s)
  78. }
  79. return fmt.Sprintf("%x", h.Sum(nil))
  80. }
  81. //RandomStr 随机生成字符串
  82. func RandomStr(length int) string {
  83. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  84. bytes := []byte(str)
  85. result := []byte{}
  86. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  87. for i := 0; i < length; i++ {
  88. result = append(result, bytes[r.Intn(len(bytes))])
  89. }
  90. return string(result)
  91. }
  92. //GetCurrTs return current timestamps
  93. func GetCurrTs() int64 {
  94. return time.Now().Unix()
  95. }
  96. func SetThisRequestURI(uri string) string {
  97. return fmt.Sprintf("%v%v", beego.AppConfig.String("httpdomain"), uri)
  98. }
  99. func SetThisBasr64RequestURI(uri string) string {
  100. backUrl := fmt.Sprintf("%v%v", beego.AppConfig.String("httpdomain"), uri)
  101. backUrl = base64.URLEncoding.EncodeToString([]byte(backUrl))
  102. return backUrl
  103. }
  104. func TransNum2Str(read int64) (transRead string) {
  105. if read < 0 {
  106. transRead = "0"
  107. } else if read < 10000 {
  108. transRead = fmt.Sprintf("%v", read)
  109. } else {
  110. var c float64 = 10000
  111. var rc float64 = float64(read)
  112. transRead = fmt.Sprintf("%.2f万", rc/c)
  113. }
  114. return
  115. }
  116. func GenMobileToken(mobile string) (token string) {
  117. st := strings.Split(mobile, "")
  118. s := fmt.Sprintf("%s%v%v%v%v%v%v", mobile, st[0], st[1], st[3], st[7], st[6], st[9])
  119. h := sha1.New()
  120. h.Write([]byte(s))
  121. bs := h.Sum(nil)
  122. token = fmt.Sprintf("%x", bs)
  123. return
  124. }
  125. func CheckMobileToken(mobile, token string) bool {
  126. o := GenMobileToken(mobile)
  127. if token == o {
  128. return true
  129. }
  130. return false
  131. }
  132. type jSapiConfig struct {
  133. AppID string `json:"app_id"`
  134. Timestamp int64 `json:"timestamp"`
  135. NonceStr string `json:"nonce_str"`
  136. Signature string `json:"signature"`
  137. }
  138. //GetAJTConfig jsapi_ticket config
  139. func GetAJTConfig(jsapiTicket, uri string) (jSapiConfig, error) {
  140. var config jSapiConfig
  141. nonceStr := RandomStr(16)
  142. timestamp := GetCurrTs()
  143. str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", jsapiTicket, nonceStr, timestamp, uri)
  144. sigStr := Signature(str)
  145. config.AppID = beego.AppConfig.String("wxappId")
  146. config.NonceStr = nonceStr
  147. config.Timestamp = timestamp
  148. config.Signature = sigStr
  149. return config, nil
  150. }
  151. func TrimHtml(src string) string {
  152. //将HTML标签全转换成小写
  153. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  154. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  155. //去除STYLE
  156. re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
  157. src = re.ReplaceAllString(src, "")
  158. //去除SCRIPT
  159. re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
  160. src = re.ReplaceAllString(src, "")
  161. //去除所有尖括号内的HTML代码,并换成换行符
  162. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  163. src = re.ReplaceAllString(src, "\n")
  164. //去除连续的换行符
  165. re, _ = regexp.Compile("\\s{2,}")
  166. src = re.ReplaceAllString(src, "\n")
  167. return strings.TrimSpace(src)
  168. }
  169. func SubString(str string, begin, length int) string {
  170. rs := []rune(str)
  171. lth := len(rs)
  172. if begin < 0 {
  173. begin = 0
  174. }
  175. if begin >= lth {
  176. begin = lth
  177. }
  178. end := begin + length
  179. if end > lth {
  180. end = lth
  181. }
  182. return string(rs[begin:end])
  183. }
  184. func ParseTimeStringToTime(layout string, timeStr string) (*time.Time, error) {
  185. if len(layout) == 0 || len(timeStr) == 0 {
  186. return nil, errors.New("layout 或 日期字符串 为空,无法解析")
  187. }
  188. loc, _ := time.LoadLocation("Local")
  189. date, parseDateErr := time.ParseInLocation(layout, timeStr, loc)
  190. return &date, parseDateErr
  191. }
  192. // 获取 date 所在周的周一和周日,以周一0点为一周的开始,周日24点为一周的结束
  193. func GetMondayAndSundayOfWeekDate(date *time.Time) (time.Time, time.Time) {
  194. if date == nil {
  195. now := time.Now()
  196. date = &now
  197. }
  198. weekday := int(date.Weekday())
  199. if weekday == 0 {
  200. weekday = 7
  201. }
  202. loc, _ := time.LoadLocation("Local")
  203. monday, _ := time.ParseInLocation("2006-01-02 15:04:05", date.AddDate(0, 0, 1-weekday).Format("2006-01-02")+" 00:00:00", loc)
  204. sunday, _ := time.ParseInLocation("2006-01-02 15:04:05", date.AddDate(0, 0, 7-weekday).Format("2006-01-02")+" 23:59:59", loc)
  205. return monday, sunday
  206. }