common.go 25 KB

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