common.go 26 KB

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