common.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/PuerkitoBio/goquery"
  10. "html"
  11. "image"
  12. "image/png"
  13. "math"
  14. "math/rand"
  15. "net"
  16. "os"
  17. "os/exec"
  18. "regexp"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "unicode/utf8"
  23. )
  24. // 随机数种子
  25. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  26. func GetRandString(size int) string {
  27. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  28. randomSb := ""
  29. digitSize := len(allLetterDigit)
  30. for i := 0; i < size; i++ {
  31. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  32. }
  33. return randomSb
  34. }
  35. func GetRandStringNoSpecialChar(size int) string {
  36. 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"}
  37. randomSb := ""
  38. digitSize := len(allLetterDigit)
  39. for i := 0; i < size; i++ {
  40. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  41. }
  42. return randomSb
  43. }
  44. func StringsToJSON(str string) string {
  45. rs := []rune(str)
  46. jsons := ""
  47. for _, r := range rs {
  48. rint := int(r)
  49. if rint < 128 {
  50. jsons += string(r)
  51. } else {
  52. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  53. }
  54. }
  55. return jsons
  56. }
  57. // 序列化
  58. func ToString(v interface{}) string {
  59. data, _ := json.Marshal(v)
  60. return string(data)
  61. }
  62. // md5加密
  63. func MD5(data string) string {
  64. m := md5.Sum([]byte(data))
  65. return hex.EncodeToString(m[:])
  66. }
  67. // 获取数字随机字符
  68. func GetRandDigit(n int) string {
  69. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  70. }
  71. // 获取随机数
  72. func GetRandNumber(n int) int {
  73. return rnd.Intn(n)
  74. }
  75. func GetRandInt(min, max int) int {
  76. if min >= max || min == 0 || max == 0 {
  77. return max
  78. }
  79. return rand.Intn(max-min) + min
  80. }
  81. func GetToday(format string) string {
  82. today := time.Now().Format(format)
  83. return today
  84. }
  85. // 获取今天剩余秒数
  86. func GetTodayLastSecond() time.Duration {
  87. today := GetToday(FormatDate) + " 23:59:59"
  88. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  89. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  90. }
  91. // 处理出生日期函数
  92. func GetBrithDate(idcard string) string {
  93. l := len(idcard)
  94. var s string
  95. if l == 15 {
  96. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  97. return s
  98. }
  99. if l == 18 {
  100. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  101. return s
  102. }
  103. return GetToday(FormatDate)
  104. }
  105. // 处理性别
  106. func WhichSexByIdcard(idcard string) string {
  107. var sexs = [2]string{"女", "男"}
  108. length := len(idcard)
  109. if length == 18 {
  110. sex, _ := strconv.Atoi(string(idcard[16]))
  111. return sexs[sex%2]
  112. } else if length == 15 {
  113. sex, _ := strconv.Atoi(string(idcard[14]))
  114. return sexs[sex%2]
  115. }
  116. return "男"
  117. }
  118. // 截取小数点后几位
  119. func SubFloatToString(f float64, m int) string {
  120. n := strconv.FormatFloat(f, 'f', -1, 64)
  121. if n == "" {
  122. return ""
  123. }
  124. if m >= len(n) {
  125. return n
  126. }
  127. newn := strings.Split(n, ".")
  128. if m == 0 {
  129. return newn[0]
  130. }
  131. if len(newn) < 2 || m >= len(newn[1]) {
  132. return n
  133. }
  134. return newn[0] + "." + newn[1][:m]
  135. }
  136. // 截取小数点后几位
  137. func SubFloatToFloat(f float64, m int) float64 {
  138. newn := SubFloatToString(f, m)
  139. newf, _ := strconv.ParseFloat(newn, 64)
  140. return newf
  141. }
  142. // 获取相差时间-年
  143. func GetYearDiffer(start_time, end_time string) int {
  144. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  145. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  146. age := t2.Year() - t1.Year()
  147. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  148. age--
  149. }
  150. return age
  151. }
  152. // 获取相差时间-秒
  153. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  154. diff := end_time.Unix() - start_time.Unix()
  155. return diff
  156. }
  157. func FixFloat(f float64, m int) float64 {
  158. newn := SubFloatToString(f+0.00000001, m)
  159. newf, _ := strconv.ParseFloat(newn, 64)
  160. return newf
  161. }
  162. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  163. func StrListToString(strList []string) (str string) {
  164. if len(strList) > 0 {
  165. for k, v := range strList {
  166. if k == 0 {
  167. str = v
  168. } else {
  169. str = str + "," + v
  170. }
  171. }
  172. return
  173. }
  174. return ""
  175. }
  176. // Token
  177. func GetToken() string {
  178. randStr := GetRandString(64)
  179. token := MD5(randStr + Md5Key)
  180. tokenLen := 64 - len(token)
  181. return strings.ToUpper(token + GetRandString(tokenLen))
  182. }
  183. // 数据没有记录
  184. func ErrNoRow() string {
  185. return "<QuerySeter> no row found"
  186. }
  187. // 校验邮箱格式
  188. func ValidateEmailFormatat(email string) bool {
  189. reg := regexp.MustCompile(RegularEmail)
  190. return reg.MatchString(email)
  191. }
  192. // 验证是否是手机号
  193. func ValidateMobileFormatat(mobileNum string) bool {
  194. reg := regexp.MustCompile(RegularMobile)
  195. return reg.MatchString(mobileNum)
  196. }
  197. // 验证是否是固定电话
  198. func ValidateFixedTelephoneFormatat(mobileNum string) bool {
  199. reg := regexp.MustCompile(RegularFixedTelephone)
  200. return reg.MatchString(mobileNum)
  201. }
  202. // 判断文件是否存在
  203. func FileIsExist(filePath string) bool {
  204. _, err := os.Stat(filePath)
  205. return err == nil || os.IsExist(err)
  206. }
  207. // 获取图片扩展名
  208. func GetImgExt(file string) (ext string, err error) {
  209. var headerByte []byte
  210. headerByte = make([]byte, 8)
  211. fd, err := os.Open(file)
  212. if err != nil {
  213. return "", err
  214. }
  215. defer fd.Close()
  216. _, err = fd.Read(headerByte)
  217. if err != nil {
  218. return "", err
  219. }
  220. xStr := fmt.Sprintf("%x", headerByte)
  221. switch {
  222. case xStr == "89504e470d0a1a0a":
  223. ext = ".png"
  224. case xStr == "0000010001002020":
  225. ext = ".ico"
  226. case xStr == "0000020001002020":
  227. ext = ".cur"
  228. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  229. ext = ".gif"
  230. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  231. ext = ".tga"
  232. case xStr[:8] == "464f524d":
  233. ext = ".iff"
  234. case xStr[:8] == "52494646":
  235. ext = ".ani"
  236. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  237. ext = ".tiff"
  238. case xStr[:4] == "424d":
  239. ext = ".bmp"
  240. case xStr[:4] == "ffd8":
  241. ext = ".jpg"
  242. case xStr[:2] == "0a":
  243. ext = ".pcx"
  244. default:
  245. ext = ""
  246. }
  247. return ext, nil
  248. }
  249. // 保存图片
  250. func SaveImage(path string, img image.Image) (err error) {
  251. //需要保持的文件
  252. imgfile, err := os.Create(path)
  253. defer imgfile.Close()
  254. // 以PNG格式保存文件
  255. err = png.Encode(imgfile, img)
  256. return err
  257. }
  258. // 保存base64数据为文件
  259. func SaveBase64ToFile(content, path string) error {
  260. data, err := base64.StdEncoding.DecodeString(content)
  261. if err != nil {
  262. return err
  263. }
  264. f, err := os.Create(path)
  265. defer f.Close()
  266. if err != nil {
  267. return err
  268. }
  269. f.Write(data)
  270. return nil
  271. }
  272. func SaveBase64ToFileBySeek(content, path string) (err error) {
  273. data, err := base64.StdEncoding.DecodeString(content)
  274. exist, err := PathExists(path)
  275. if err != nil {
  276. return
  277. }
  278. if !exist {
  279. f, err := os.Create(path)
  280. if err != nil {
  281. return err
  282. }
  283. n, _ := f.Seek(0, 2)
  284. // 从末尾的偏移量开始写入内容
  285. _, err = f.WriteAt([]byte(data), n)
  286. defer f.Close()
  287. } else {
  288. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  289. if err != nil {
  290. return err
  291. }
  292. n, _ := f.Seek(0, 2)
  293. // 从末尾的偏移量开始写入内容
  294. _, err = f.WriteAt([]byte(data), n)
  295. defer f.Close()
  296. }
  297. return nil
  298. }
  299. func PathExists(path string) (bool, error) {
  300. _, err := os.Stat(path)
  301. if err == nil {
  302. return true, nil
  303. }
  304. if os.IsNotExist(err) {
  305. return false, nil
  306. }
  307. return false, err
  308. }
  309. func StartIndex(page, pagesize int) int {
  310. if page > 1 {
  311. return (page - 1) * pagesize
  312. }
  313. return 0
  314. }
  315. func PageCount(count, pagesize int) int {
  316. if count%pagesize > 0 {
  317. return count/pagesize + 1
  318. } else {
  319. return count / pagesize
  320. }
  321. }
  322. func TrimHtml(src string) string {
  323. //将HTML标签全转换成小写
  324. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  325. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  326. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  327. src = re.ReplaceAllString(src, "[图片]")
  328. re, _ = regexp.Compile("class[\\S\\s]+?>")
  329. src = re.ReplaceAllString(src, "")
  330. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  331. src = re.ReplaceAllString(src, "")
  332. return strings.TrimSpace(src)
  333. }
  334. //1556164246 -> 2019-04-25 03:50:46 +0000
  335. //timestamp
  336. func TimeToTimestamp() {
  337. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  338. }
  339. func ToUnicode(text string) string {
  340. textQuoted := strconv.QuoteToASCII(text)
  341. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  342. return textUnquoted
  343. }
  344. func VersionToInt(version string) int {
  345. version = strings.Replace(version, ".", "", -1)
  346. n, _ := strconv.Atoi(version)
  347. return n
  348. }
  349. func IsCheckInList(list []int, s int) bool {
  350. for _, v := range list {
  351. if v == s {
  352. return true
  353. }
  354. }
  355. return false
  356. }
  357. func round(num float64) int {
  358. return int(num + math.Copysign(0.5, num))
  359. }
  360. func toFixed(num float64, precision int) float64 {
  361. output := math.Pow(10, float64(precision))
  362. return float64(round(num*output)) / output
  363. }
  364. // GetWilsonScore returns Wilson Score
  365. func GetWilsonScore(p, n float64) float64 {
  366. if p == 0 && n == 0 {
  367. return 0
  368. }
  369. return toFixed(((p+1.9208)/(p+n)-1.96*math.Sqrt(p*n/(p+n)+0.9604)/(p+n))/(1+3.8416/(p+n)), 2)
  370. }
  371. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  372. func ChangeWordsToNum(str string) (numStr string) {
  373. words := ([]rune)(str)
  374. num := 0
  375. n := 0
  376. for i := 0; i < len(words); i++ {
  377. word := string(words[i : i+1])
  378. switch word {
  379. case "万":
  380. if n == 0 {
  381. n = 1
  382. }
  383. n = n * 10000
  384. num = num*10000 + n
  385. n = 0
  386. case "千":
  387. if n == 0 {
  388. n = 1
  389. }
  390. n = n * 1000
  391. num += n
  392. n = 0
  393. case "百":
  394. if n == 0 {
  395. n = 1
  396. }
  397. n = n * 100
  398. num += n
  399. n = 0
  400. case "十":
  401. if n == 0 {
  402. n = 1
  403. }
  404. n = n * 10
  405. num += n
  406. n = 0
  407. case "一":
  408. n += 1
  409. case "二":
  410. n += 2
  411. case "三":
  412. n += 3
  413. case "四":
  414. n += 4
  415. case "五":
  416. n += 5
  417. case "六":
  418. n += 6
  419. case "七":
  420. n += 7
  421. case "八":
  422. n += 8
  423. case "九":
  424. n += 9
  425. case "零":
  426. default:
  427. if n > 0 {
  428. num += n
  429. n = 0
  430. }
  431. if num == 0 {
  432. numStr += word
  433. } else {
  434. numStr += strconv.Itoa(num) + word
  435. num = 0
  436. }
  437. }
  438. }
  439. if n > 0 {
  440. num += n
  441. n = 0
  442. }
  443. if num != 0 {
  444. numStr += strconv.Itoa(num)
  445. }
  446. return
  447. }
  448. func Sha1(data string) string {
  449. sha1 := sha1.New()
  450. sha1.Write([]byte(data))
  451. return hex.EncodeToString(sha1.Sum([]byte("")))
  452. }
  453. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  454. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  455. out, err := exec.Command("bash", "-c", cmd).Output()
  456. if err != nil {
  457. return
  458. }
  459. outTimes := string(out)
  460. fmt.Println("outTimes:", outTimes)
  461. if outTimes != "" {
  462. timeArr := strings.Split(outTimes, ":")
  463. h := timeArr[0]
  464. m := timeArr[1]
  465. s := timeArr[2]
  466. hInt, err := strconv.Atoi(h)
  467. if err != nil {
  468. return playSeconds, err
  469. }
  470. mInt, err := strconv.Atoi(m)
  471. if err != nil {
  472. return playSeconds, err
  473. }
  474. s = strings.Trim(s, " ")
  475. s = strings.Trim(s, "\n")
  476. sInt, err := strconv.ParseFloat(s, 64)
  477. if err != nil {
  478. return playSeconds, err
  479. }
  480. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  481. }
  482. return
  483. }
  484. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  485. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  486. tradeCode = strings.Trim(tradeCode, " ")
  487. tradeCodeInt, err := strconv.Atoi(tradeCode)
  488. if err != nil {
  489. return
  490. }
  491. tradeCodeInt = tradeCodeInt + 1
  492. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  493. return
  494. }
  495. // excel日期字段格式化 yyyy-mm-dd
  496. func ConvertToFormatDay(excelDaysString string) string {
  497. // 2006-01-02 距离 1900-01-01的天数
  498. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  499. curDiffDay := excelDaysString
  500. b, _ := strconv.Atoi(curDiffDay)
  501. // 获取excel的日期距离2006-01-02的天数
  502. realDiffDay := b - baseDiffDay
  503. //fmt.Println("realDiffDay:",realDiffDay)
  504. // 距离2006-01-02 秒数
  505. realDiffSecond := realDiffDay * 24 * 3600
  506. //fmt.Println("realDiffSecond:",realDiffSecond)
  507. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  508. baseOriginSecond := 1136185445
  509. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  510. return resultTime
  511. }
  512. // 字符串转换为time
  513. func StrTimeToTime(strTime string) time.Time {
  514. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  515. loc, _ := time.LoadLocation("Local") //重要:获取时区
  516. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  517. return resultTime
  518. }
  519. // 时间格式去掉时分秒
  520. func TimeRemoveHms(strTime string) string {
  521. var Ymd string
  522. var resultTime = StrTimeToTime(strTime)
  523. year := resultTime.Year()
  524. month := resultTime.Format("01")
  525. day1 := resultTime.Day()
  526. if day1 < 10 {
  527. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  528. } else {
  529. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  530. }
  531. return Ymd
  532. }
  533. // 判断时间是当年的第几周
  534. func WeekByDate(t time.Time) string {
  535. var resultSAtr string
  536. t = t.AddDate(0, 0, -8) // 减少八天跟老数据标题统一
  537. yearDay := t.YearDay()
  538. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  539. firstDayInWeek := int(yearFirstDay.Weekday())
  540. //今年第一周有几天
  541. firstWeekDays := 1
  542. if firstDayInWeek != 0 {
  543. firstWeekDays = 7 - firstDayInWeek + 1
  544. }
  545. var week int
  546. if yearDay <= firstWeekDays {
  547. week = 1
  548. } else {
  549. week = (yearDay-firstWeekDays)/7 + 2
  550. }
  551. resultSAtr = "(" + strconv.Itoa(t.Year()) + "年第" + strconv.Itoa(week) + "周" + ")"
  552. return resultSAtr
  553. }
  554. func Mp3Time(videoPlaySeconds string) string {
  555. var d int
  556. var timeStr string
  557. a, _ := strconv.ParseFloat(videoPlaySeconds, 32)
  558. b := int(a)
  559. c := b % 60
  560. d = b / 60
  561. if b <= 60 {
  562. timeStr = "00:" + strconv.Itoa(b)
  563. } else {
  564. if d < 10 {
  565. timeStr = "0" + strconv.Itoa(d) + ":" + strconv.Itoa(c)
  566. } else {
  567. timeStr = strconv.Itoa(d) + ":" + strconv.Itoa(c)
  568. }
  569. }
  570. return timeStr
  571. }
  572. func GetLocalIP() (ip string, err error) {
  573. addrs, err := net.InterfaceAddrs()
  574. if err != nil {
  575. return
  576. }
  577. for _, addr := range addrs {
  578. ipAddr, ok := addr.(*net.IPNet)
  579. if !ok {
  580. continue
  581. }
  582. if ipAddr.IP.IsLoopback() {
  583. continue
  584. }
  585. if !ipAddr.IP.IsGlobalUnicast() {
  586. continue
  587. }
  588. return ipAddr.IP.String(), nil
  589. }
  590. return
  591. }
  592. // GetOrmInReplace 获取orm的in查询替换?的方法
  593. func GetOrmInReplace(num int) string {
  594. template := make([]string, num)
  595. for i := 0; i < num; i++ {
  596. template[i] = "?"
  597. }
  598. return strings.Join(template, ",")
  599. }
  600. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  601. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  602. for _, id := range idStrList {
  603. if id == searchId {
  604. has = true
  605. return
  606. }
  607. }
  608. return
  609. }
  610. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  611. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  612. for _, id := range idIntList {
  613. if id == searchId {
  614. has = true
  615. return
  616. }
  617. }
  618. return
  619. }
  620. // GetNowWeekMonday 获取本周周一的时间
  621. func GetNowWeekMonday() time.Time {
  622. offset := int(time.Monday - time.Now().Weekday())
  623. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  624. offset = -6
  625. }
  626. mondayTime := time.Now().AddDate(0, 0, offset)
  627. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  628. return mondayTime
  629. }
  630. // GetLastWeekMonday 获取上周周一的时间
  631. func GetLastWeekMonday() time.Time {
  632. offset := int(time.Monday - time.Now().Weekday())
  633. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  634. offset = -6
  635. }
  636. mondayTime := time.Now().AddDate(0, 0, offset-7)
  637. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  638. return mondayTime
  639. }
  640. // GetNowWeekSunDay 获取本周周日的时间
  641. func GetNowWeekSunday() time.Time {
  642. return GetNowWeekMonday().AddDate(0, 0, 6)
  643. }
  644. // GetLastWeekSunday 获取上周周日的时间
  645. func GetLastWeekSunday() time.Time {
  646. return GetLastWeekMonday().AddDate(0, 0, 6)
  647. }
  648. // GetNowMonthFirstDay 获取本月第一天的时间
  649. func GetNowMonthFirstDay() time.Time {
  650. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  651. return nowMonthFirstDay
  652. }
  653. // GetNowMonthLastDay 获取本月最后一天的时间
  654. func GetNowMonthLastDay() time.Time {
  655. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  656. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  657. return nowMonthLastDay
  658. }
  659. // GetNowMonthFirstDay 获取上月第一天的时间
  660. func GetLastMonthFirstDay() time.Time {
  661. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location())
  662. return nowMonthFirstDay
  663. }
  664. // GetNowMonthLastDay 获取上月最后一天的时间
  665. func GetLastMonthLastDay() time.Time {
  666. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  667. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  668. return nowMonthLastDay
  669. }
  670. // 时间格式去掉时分秒
  671. func TimeRemoveHms2(strTime string) string {
  672. var Ymd string
  673. var resultTime = StrTimeToTime(strTime)
  674. year := resultTime.Year()
  675. month := resultTime.Format("01")
  676. day1 := resultTime.Day()
  677. if day1 < 10 {
  678. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  679. } else {
  680. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  681. }
  682. return Ymd
  683. }
  684. // 时间格式去掉年
  685. func GetTimeDateRemoveYear(strTime string) (dataStr string) {
  686. slicePublishTime := strings.Split(strTime, "-")
  687. for k, v := range slicePublishTime {
  688. if k == 0 {
  689. continue
  690. }
  691. dataStr += v + "-"
  692. }
  693. dataStr = strings.TrimRight(dataStr, "-")
  694. return dataStr
  695. }
  696. // 时间格式去掉年和秒
  697. func GetTimeDateRemoveYearAndSecond(strTime string) (dataStr string) {
  698. slicePublishTime := strings.Split(strTime, "-")
  699. for k, v := range slicePublishTime {
  700. if k == 0 {
  701. continue
  702. }
  703. dataStr += v + "-"
  704. }
  705. dataStr = strings.TrimRight(dataStr, "-")
  706. dataStr = dataStr[:len(dataStr)-3]
  707. return
  708. }
  709. func ArticleHasImgUrl(body string) (hasImg bool, err error) {
  710. r := strings.NewReader(string(body))
  711. doc, err := goquery.NewDocumentFromReader(r)
  712. if err != nil {
  713. fmt.Println(err)
  714. }
  715. doc.Find("img").Each(func(i int, s *goquery.Selection) {
  716. hasImg = true
  717. })
  718. return
  719. }
  720. func ArticleRemoveImgUrl(body string) (result string) {
  721. // 使用正则表达式去除img标签
  722. re := regexp.MustCompile(`<img[^>]*>`)
  723. result = re.ReplaceAllString(body, "")
  724. return
  725. }
  726. func FindArticleImgUrls(body string) (imgUrls []string, err error) {
  727. r := strings.NewReader(string(body))
  728. doc, err := goquery.NewDocumentFromReader(r)
  729. if err != nil {
  730. fmt.Println(err)
  731. }
  732. doc.Find("img").Each(func(i int, s *goquery.Selection) {
  733. src, _ := s.Attr("src")
  734. imgUrls = append(imgUrls, src)
  735. })
  736. return
  737. }
  738. // 去除部分style
  739. func ExtractText(body string) (result string, err error) {
  740. // 使用正则表达式去除img标签
  741. re := regexp.MustCompile(`<section style[\s\S]*?>`)
  742. result = re.ReplaceAllString(body, "")
  743. re = regexp.MustCompile(`<span style[\s\S]*?>`)
  744. result = re.ReplaceAllString(result, "")
  745. return
  746. }
  747. // 富文本字符串截取指定长度
  748. func InterceptHtmlLength(body string, length int) (newbody string) {
  749. content := html.UnescapeString(body)
  750. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  751. if err != nil {
  752. fmt.Println("create doc err:", err.Error())
  753. return
  754. }
  755. bodyText := doc.Text()
  756. if len(bodyText) < length {
  757. length = len(bodyText)
  758. }
  759. newbody = bodyText[0:length]
  760. return
  761. }
  762. // 处理活动名称
  763. func TruncateActivityNameString(s string) string {
  764. // 计算字符串总字数(按汉字、数字、字母和特殊符号计算)
  765. totalCharCount := utf8.RuneCountInString(s)
  766. // 如果总字数不超过18,则直接返回整个字符串
  767. if totalCharCount <= 18 {
  768. return s
  769. }
  770. // 计算前15个汉字所需的字节位置
  771. hanziCount := 0
  772. byteIndex := 0
  773. for byteIndex < len(s) && hanziCount < 15 {
  774. r, size := utf8.DecodeRuneInString(s[byteIndex:])
  775. if r != utf8.RuneError {
  776. hanziCount++
  777. }
  778. byteIndex += size
  779. }
  780. // 截取前15个汉字,并添加省略号
  781. return s[:byteIndex] + "…"
  782. }