tools.go 6.6KB

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