tools.go 6.3KB

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