common.go 23 KB

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