common.go 23 KB

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