common.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/md5"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "fmt"
  11. "image"
  12. "image/png"
  13. "math"
  14. "math/rand"
  15. "net"
  16. "net/http"
  17. "os"
  18. "os/exec"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  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. // HmacMd5 HmacMd5加密
  68. func HmacMd5(key, data string) string {
  69. h := hmac.New(md5.New, []byte(key))
  70. h.Write([]byte(data))
  71. return hex.EncodeToString(h.Sum([]byte("")))
  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 FileIsExist(filePath string) bool {
  205. _, err := os.Stat(filePath)
  206. return err == nil || os.IsExist(err)
  207. }
  208. // 获取图片扩展名
  209. func GetImgExt(file string) (ext string, err error) {
  210. var headerByte []byte
  211. headerByte = make([]byte, 8)
  212. fd, err := os.Open(file)
  213. if err != nil {
  214. return "", err
  215. }
  216. defer fd.Close()
  217. _, err = fd.Read(headerByte)
  218. if err != nil {
  219. return "", err
  220. }
  221. xStr := fmt.Sprintf("%x", headerByte)
  222. switch {
  223. case xStr == "89504e470d0a1a0a":
  224. ext = ".png"
  225. case xStr == "0000010001002020":
  226. ext = ".ico"
  227. case xStr == "0000020001002020":
  228. ext = ".cur"
  229. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  230. ext = ".gif"
  231. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  232. ext = ".tga"
  233. case xStr[:8] == "464f524d":
  234. ext = ".iff"
  235. case xStr[:8] == "52494646":
  236. ext = ".ani"
  237. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  238. ext = ".tiff"
  239. case xStr[:4] == "424d":
  240. ext = ".bmp"
  241. case xStr[:4] == "ffd8":
  242. ext = ".jpg"
  243. case xStr[:2] == "0a":
  244. ext = ".pcx"
  245. default:
  246. ext = ""
  247. }
  248. return ext, nil
  249. }
  250. // 保存图片
  251. func SaveImage(path string, img image.Image) (err error) {
  252. //需要保持的文件
  253. imgfile, err := os.Create(path)
  254. defer imgfile.Close()
  255. // 以PNG格式保存文件
  256. err = png.Encode(imgfile, img)
  257. return err
  258. }
  259. // 保存base64数据为文件
  260. func SaveBase64ToFile(content, path string) error {
  261. data, err := base64.StdEncoding.DecodeString(content)
  262. if err != nil {
  263. return err
  264. }
  265. f, err := os.Create(path)
  266. defer f.Close()
  267. if err != nil {
  268. return err
  269. }
  270. f.Write(data)
  271. return nil
  272. }
  273. func SaveBase64ToFileBySeek(content, path string) (err error) {
  274. data, err := base64.StdEncoding.DecodeString(content)
  275. exist, err := PathExists(path)
  276. if err != nil {
  277. return
  278. }
  279. if !exist {
  280. f, err := os.Create(path)
  281. if err != nil {
  282. return err
  283. }
  284. n, _ := f.Seek(0, 2)
  285. // 从末尾的偏移量开始写入内容
  286. _, err = f.WriteAt([]byte(data), n)
  287. defer f.Close()
  288. } else {
  289. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  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. }
  298. return nil
  299. }
  300. func PathExists(path string) (bool, error) {
  301. _, err := os.Stat(path)
  302. if err == nil {
  303. return true, nil
  304. }
  305. if os.IsNotExist(err) {
  306. return false, nil
  307. }
  308. return false, err
  309. }
  310. func StartIndex(page, pagesize int) int {
  311. if page > 1 {
  312. return (page - 1) * pagesize
  313. }
  314. return 0
  315. }
  316. func PageCount(count, pagesize int) int {
  317. if count%pagesize > 0 {
  318. return count/pagesize + 1
  319. } else {
  320. return count / pagesize
  321. }
  322. }
  323. func TrimHtml(src string) string {
  324. //将HTML标签全转换成小写
  325. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  326. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  327. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  328. src = re.ReplaceAllString(src, "[图片]")
  329. re, _ = regexp.Compile("class[\\S\\s]+?>")
  330. src = re.ReplaceAllString(src, "")
  331. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  332. src = re.ReplaceAllString(src, "")
  333. return strings.TrimSpace(src)
  334. }
  335. //1556164246 -> 2019-04-25 03:50:46 +0000
  336. //timestamp
  337. func TimeToTimestamp() {
  338. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  339. }
  340. func ToUnicode(text string) string {
  341. textQuoted := strconv.QuoteToASCII(text)
  342. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  343. return textUnquoted
  344. }
  345. func VersionToInt(version string) int {
  346. version = strings.Replace(version, ".", "", -1)
  347. n, _ := strconv.Atoi(version)
  348. return n
  349. }
  350. func IsCheckInList(list []int, s int) bool {
  351. for _, v := range list {
  352. if v == s {
  353. return true
  354. }
  355. }
  356. return false
  357. }
  358. func round(num float64) int {
  359. return int(num + math.Copysign(0.5, num))
  360. }
  361. func toFixed(num float64, precision int) float64 {
  362. output := math.Pow(10, float64(precision))
  363. return float64(round(num*output)) / output
  364. }
  365. // GetWilsonScore returns Wilson Score
  366. func GetWilsonScore(p, n float64) float64 {
  367. if p == 0 && n == 0 {
  368. return 0
  369. }
  370. 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)
  371. }
  372. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  373. func ChangeWordsToNum(str string) (numStr string) {
  374. words := ([]rune)(str)
  375. num := 0
  376. n := 0
  377. for i := 0; i < len(words); i++ {
  378. word := string(words[i : i+1])
  379. switch word {
  380. case "万":
  381. if n == 0 {
  382. n = 1
  383. }
  384. n = n * 10000
  385. num = num*10000 + n
  386. n = 0
  387. case "千":
  388. if n == 0 {
  389. n = 1
  390. }
  391. n = n * 1000
  392. num += n
  393. n = 0
  394. case "百":
  395. if n == 0 {
  396. n = 1
  397. }
  398. n = n * 100
  399. num += n
  400. n = 0
  401. case "十":
  402. if n == 0 {
  403. n = 1
  404. }
  405. n = n * 10
  406. num += n
  407. n = 0
  408. case "一":
  409. n += 1
  410. case "二":
  411. n += 2
  412. case "三":
  413. n += 3
  414. case "四":
  415. n += 4
  416. case "五":
  417. n += 5
  418. case "六":
  419. n += 6
  420. case "七":
  421. n += 7
  422. case "八":
  423. n += 8
  424. case "九":
  425. n += 9
  426. case "零":
  427. default:
  428. if n > 0 {
  429. num += n
  430. n = 0
  431. }
  432. if num == 0 {
  433. numStr += word
  434. } else {
  435. numStr += strconv.Itoa(num) + word
  436. num = 0
  437. }
  438. }
  439. }
  440. if n > 0 {
  441. num += n
  442. n = 0
  443. }
  444. if num != 0 {
  445. numStr += strconv.Itoa(num)
  446. }
  447. return
  448. }
  449. func Sha1(data string) string {
  450. sha1 := sha1.New()
  451. sha1.Write([]byte(data))
  452. return hex.EncodeToString(sha1.Sum([]byte("")))
  453. }
  454. func GetWeekDay() (weekStr string) {
  455. nowWeek := time.Now().Weekday().String()
  456. switch nowWeek {
  457. case "Monday":
  458. weekStr = "周一"
  459. break
  460. case "Tuesday":
  461. weekStr = "周二"
  462. break
  463. case "Wednesday":
  464. weekStr = "周三"
  465. break
  466. case "Thursday":
  467. weekStr = "周四"
  468. break
  469. case "Friday":
  470. weekStr = "周五"
  471. break
  472. case "Saturday":
  473. weekStr = "周六"
  474. break
  475. case "Sunday":
  476. weekStr = "周日"
  477. break
  478. default:
  479. weekStr = ""
  480. break
  481. }
  482. return
  483. }
  484. // GetNowWeekMonday 获取本周周一的时间
  485. func GetNowWeekMonday() time.Time {
  486. offset := int(time.Monday - time.Now().Weekday())
  487. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  488. offset = -6
  489. }
  490. mondayTime := time.Now().AddDate(0, 0, offset)
  491. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  492. return mondayTime
  493. }
  494. // GetLastWeekMonday 获取上周周一的时间
  495. func GetLastWeekMonday() time.Time {
  496. offset := int(time.Monday - time.Now().Weekday())
  497. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  498. offset = -6
  499. }
  500. mondayTime := time.Now().AddDate(0, 0, offset-7)
  501. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  502. return mondayTime
  503. }
  504. // GetNowWeekTuesday 获取本周周二的时间
  505. func GetNowWeekTuesday() time.Time {
  506. offset := int(time.Tuesday - time.Now().Weekday())
  507. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  508. offset = -6
  509. }
  510. mondayTime := time.Now().AddDate(0, 0, offset)
  511. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  512. return mondayTime
  513. }
  514. // GetLastWeekTuesday 获取上周周二的时间
  515. func GetLastWeekTuesday() time.Time {
  516. offset := int(time.Tuesday - time.Now().Weekday())
  517. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  518. offset = -6
  519. }
  520. mondayTime := time.Now().AddDate(0, 0, offset-7)
  521. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  522. return mondayTime
  523. }
  524. // GetNowWeekFriday 获取本周周四的时间
  525. func GetNowWeekThursday() time.Time {
  526. offset := int(time.Thursday - time.Now().Weekday())
  527. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  528. offset = -6
  529. }
  530. fridayTime := time.Now().AddDate(0, 0, offset)
  531. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  532. return fridayTime
  533. }
  534. // GetLastWeekFriday 获取上周周四的时间
  535. func GetLastWeekThursday() time.Time {
  536. offset := int(time.Thursday - time.Now().Weekday())
  537. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  538. offset = -6
  539. }
  540. fridayTime := time.Now().AddDate(0, 0, offset-7)
  541. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  542. return fridayTime
  543. }
  544. // GetNowWeekFriday 获取本周周五的时间
  545. func GetNowWeekFriday() time.Time {
  546. offset := int(time.Friday - time.Now().Weekday())
  547. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  548. offset = -6
  549. }
  550. fridayTime := time.Now().AddDate(0, 0, offset)
  551. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  552. return fridayTime
  553. }
  554. // GetLastWeekFriday 获取上周周五的时间
  555. func GetLastWeekFriday() time.Time {
  556. offset := int(time.Friday - time.Now().Weekday())
  557. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  558. offset = -6
  559. }
  560. fridayTime := time.Now().AddDate(0, 0, offset-7)
  561. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  562. return fridayTime
  563. }
  564. // GetNowWeekLastDay 获取本周最后一天的时间
  565. func GetNowWeekLastDay() time.Time {
  566. offset := int(time.Monday - time.Now().Weekday())
  567. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  568. offset = -6
  569. }
  570. firstDayTime := time.Now().AddDate(0, 0, offset)
  571. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  572. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  573. return lastDayTime
  574. }
  575. // GetNowMonthFirstDay 获取本月第一天的时间
  576. func GetNowMonthFirstDay() time.Time {
  577. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  578. return nowMonthFirstDay
  579. }
  580. // GetNowMonthLastDay 获取本月最后一天的时间
  581. func GetNowMonthLastDay() time.Time {
  582. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  583. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  584. return nowMonthLastDay
  585. }
  586. // GetNowQuarterFirstDay 获取本季度第一天的时间
  587. func GetNowQuarterFirstDay() time.Time {
  588. month := int(time.Now().Month())
  589. var nowQuarterFirstDay time.Time
  590. if month >= 1 && month <= 3 {
  591. //1月1号
  592. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  593. } else if month >= 4 && month <= 6 {
  594. //4月1号
  595. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  596. } else if month >= 7 && month <= 9 {
  597. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  598. } else {
  599. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  600. }
  601. return nowQuarterFirstDay
  602. }
  603. // GetNowQuarterLastDay 获取本季度最后一天的时间
  604. func GetNowQuarterLastDay() time.Time {
  605. month := int(time.Now().Month())
  606. var nowQuarterLastDay time.Time
  607. if month >= 1 && month <= 3 {
  608. //03-31 23:59:59
  609. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  610. } else if month >= 4 && month <= 6 {
  611. //06-30 23:59:59
  612. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  613. } else if month >= 7 && month <= 9 {
  614. //09-30 23:59:59
  615. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  616. } else {
  617. //12-31 23:59:59
  618. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  619. }
  620. return nowQuarterLastDay
  621. }
  622. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  623. func GetNowHalfYearFirstDay() time.Time {
  624. month := int(time.Now().Month())
  625. var nowHalfYearLastDay time.Time
  626. if month >= 1 && month <= 6 {
  627. //03-31 23:59:59
  628. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  629. } else {
  630. //12-31 23:59:59
  631. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  632. }
  633. return nowHalfYearLastDay
  634. }
  635. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  636. func GetNowHalfYearLastDay() time.Time {
  637. month := int(time.Now().Month())
  638. var nowHalfYearLastDay time.Time
  639. if month >= 1 && month <= 6 {
  640. //03-31 23:59:59
  641. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  642. } else {
  643. //12-31 23:59:59
  644. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  645. }
  646. return nowHalfYearLastDay
  647. }
  648. // GetNowYearFirstDay 获取当前年的最后一天的时间
  649. func GetNowYearFirstDay() time.Time {
  650. //12-31 23:59:59
  651. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  652. return nowYearFirstDay
  653. }
  654. // GetNowYearLastDay 获取当前年的最后一天的时间
  655. func GetNowYearLastDay() time.Time {
  656. //12-31 23:59:59
  657. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  658. return nowYearLastDay
  659. }
  660. // SubStr 截取字符串(中文)
  661. func SubStr(str string, subLen int) string {
  662. strRune := []rune(str)
  663. bodyRuneLen := len(strRune)
  664. if bodyRuneLen > subLen {
  665. bodyRuneLen = subLen
  666. }
  667. str = string(strRune[:bodyRuneLen])
  668. return str
  669. }
  670. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  671. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  672. for _, id := range idIntList {
  673. if id == searchId {
  674. has = true
  675. return
  676. }
  677. }
  678. return
  679. }
  680. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  681. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  682. for _, id := range idStrList {
  683. if id == searchId {
  684. has = true
  685. return
  686. }
  687. }
  688. return
  689. }
  690. func GetLocalIP() (ip string, err error) {
  691. addrs, err := net.InterfaceAddrs()
  692. if err != nil {
  693. return
  694. }
  695. for _, addr := range addrs {
  696. ipAddr, ok := addr.(*net.IPNet)
  697. if !ok {
  698. continue
  699. }
  700. if ipAddr.IP.IsLoopback() {
  701. continue
  702. }
  703. if !ipAddr.IP.IsGlobalUnicast() {
  704. continue
  705. }
  706. return ipAddr.IP.String(), nil
  707. }
  708. return
  709. }
  710. // 富文本字段过滤处理
  711. func GetRichText(content string) (contentSub string) {
  712. contentSub = strings.Replace(content, "<p data-f-id=\"pbf\" style=\"text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sans-serif;\">Powered by <a href=\"https://www.froala.com/wysiwyg-editor?pb=1\" title=\"Froala Editor\">Froala Editor</a></p>", "", -1)
  713. return
  714. }
  715. // GetOrmInReplace 获取orm的in查询替换?的方法
  716. func GetOrmInReplace(num int) string {
  717. template := make([]string, num)
  718. for i := 0; i < num; i++ {
  719. template[i] = "?"
  720. }
  721. return strings.Join(template, ",")
  722. }
  723. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  724. // 将字符串转化为Time格式
  725. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  726. if err != nil {
  727. return 0, err
  728. }
  729. // 将字符串转化为Time格式
  730. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  731. if err != nil {
  732. return 0, err
  733. }
  734. //计算相差天数
  735. return int(date1.Sub(date2).Hours() / 24), nil
  736. }
  737. // SubFloatToFloatStr 截取小数点后几位
  738. func SubFloatToFloatStr(f float64, m int) string {
  739. newn := SubFloatToString(f, m)
  740. return newn
  741. }
  742. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  743. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  744. out, err := exec.Command("bash", "-c", cmd).Output()
  745. if err != nil {
  746. return
  747. }
  748. outTimes := string(out)
  749. fmt.Println("outTimes:", outTimes)
  750. if outTimes != "" {
  751. timeArr := strings.Split(outTimes, ":")
  752. h := timeArr[0]
  753. m := timeArr[1]
  754. s := timeArr[2]
  755. hInt, err := strconv.Atoi(h)
  756. if err != nil {
  757. return playSeconds, err
  758. }
  759. mInt, err := strconv.Atoi(m)
  760. if err != nil {
  761. return playSeconds, err
  762. }
  763. s = strings.Trim(s, " ")
  764. s = strings.Trim(s, "\n")
  765. sInt, err := strconv.ParseFloat(s, 64)
  766. if err != nil {
  767. return playSeconds, err
  768. }
  769. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  770. }
  771. return
  772. }
  773. // 随机手机号
  774. const letterBytes = "0123456789"
  775. const (
  776. letterIdxBits = 4
  777. letterIdxMask = 1<<letterIdxBits - 1
  778. )
  779. var src = rand.NewSource(time.Now().UnixNano())
  780. var headerNums = [...]string{"139", "138", "137", "136", "135", "134", "159", "158", "157", "150", "151", "152", "188", "187", "182", "183", "184", "178", "130", "131", "132", "156", "155", "186", "185", "176", "133", "153", "189", "180", "181", "177"}
  781. var headerNumsLen = len(headerNums)
  782. const (
  783. headerIdxBits = 6
  784. headerIdxMask = 1<<headerIdxBits - 1
  785. )
  786. func getHeaderIdx(cache int64) int {
  787. for cache > 0{
  788. idx := int(cache & headerIdxMask)
  789. if idx < headerNumsLen{
  790. return idx
  791. }
  792. cache >>= headerIdxBits
  793. }
  794. return rand.Intn(headerNumsLen)
  795. }
  796. func RandomPhone() string {
  797. b := make([]byte, 12)
  798. cache := src.Int63()
  799. headerIdx := getHeaderIdx(cache)
  800. for i := 0; i < 3; i++{
  801. b[i] = headerNums[headerIdx][i]
  802. }
  803. for i := 3; i < 12 ; {
  804. if cache == 0{
  805. cache = src.Int63()
  806. }
  807. if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
  808. b[i] = letterBytes[idx]
  809. i++
  810. }
  811. cache >>= letterIdxBits
  812. }
  813. return string(b)
  814. }
  815. // makePostRequest 发起POST请求并返回响应
  816. func MakePostRequest(url string, body []byte, headers map[string]string) (*http.Response, error) {
  817. req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
  818. if err != nil {
  819. return nil, err
  820. }
  821. // 设置自定义头部
  822. for key, value := range headers {
  823. req.Header.Set(key, value)
  824. }
  825. // 发起请求
  826. client := &http.Client{}
  827. resp, err := client.Do(req)
  828. if err != nil {
  829. return nil, err
  830. }
  831. return resp, nil
  832. }