common.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "image"
  10. "image/png"
  11. "math"
  12. "math/rand"
  13. "os"
  14. "os/exec"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. //随机数种子
  21. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  22. func GetRandString(size int) string {
  23. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  24. randomSb := ""
  25. digitSize := len(allLetterDigit)
  26. for i := 0; i < size; i++ {
  27. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  28. }
  29. return randomSb
  30. }
  31. func GetRandStringNoSpecialChar(size int) string {
  32. 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"}
  33. randomSb := ""
  34. digitSize := len(allLetterDigit)
  35. for i := 0; i < size; i++ {
  36. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  37. }
  38. return randomSb
  39. }
  40. func StringsToJSON(str string) string {
  41. rs := []rune(str)
  42. jsons := ""
  43. for _, r := range rs {
  44. rint := int(r)
  45. if rint < 128 {
  46. jsons += string(r)
  47. } else {
  48. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  49. }
  50. }
  51. return jsons
  52. }
  53. //序列化
  54. func ToString(v interface{}) string {
  55. data, _ := json.Marshal(v)
  56. return string(data)
  57. }
  58. //md5加密
  59. func MD5(data string) string {
  60. m := md5.Sum([]byte(data))
  61. return hex.EncodeToString(m[:])
  62. }
  63. // 获取数字随机字符
  64. func GetRandDigit(n int) string {
  65. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  66. }
  67. // 获取随机数
  68. func GetRandNumber(n int) int {
  69. return rnd.Intn(n)
  70. }
  71. func GetRandInt(min, max int) int {
  72. if min >= max || min == 0 || max == 0 {
  73. return max
  74. }
  75. return rand.Intn(max-min) + min
  76. }
  77. func GetToday(format string) string {
  78. today := time.Now().Format(format)
  79. return today
  80. }
  81. //获取今天剩余秒数
  82. func GetTodayLastSecond() time.Duration {
  83. today := GetToday(FormatDate) + " 23:59:59"
  84. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  85. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  86. }
  87. // 处理出生日期函数
  88. func GetBrithDate(idcard string) string {
  89. l := len(idcard)
  90. var s string
  91. if l == 15 {
  92. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  93. return s
  94. }
  95. if l == 18 {
  96. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  97. return s
  98. }
  99. return GetToday(FormatDate)
  100. }
  101. //处理性别
  102. func WhichSexByIdcard(idcard string) string {
  103. var sexs = [2]string{"女", "男"}
  104. length := len(idcard)
  105. if length == 18 {
  106. sex, _ := strconv.Atoi(string(idcard[16]))
  107. return sexs[sex%2]
  108. } else if length == 15 {
  109. sex, _ := strconv.Atoi(string(idcard[14]))
  110. return sexs[sex%2]
  111. }
  112. return "男"
  113. }
  114. //截取小数点后几位
  115. func SubFloatToString(f float64, m int) string {
  116. n := strconv.FormatFloat(f, 'f', -1, 64)
  117. if n == "" {
  118. return ""
  119. }
  120. if m >= len(n) {
  121. return n
  122. }
  123. newn := strings.Split(n, ".")
  124. if m == 0 {
  125. return newn[0]
  126. }
  127. if len(newn) < 2 || m >= len(newn[1]) {
  128. return n
  129. }
  130. return newn[0] + "." + newn[1][:m]
  131. }
  132. //截取小数点后几位
  133. func SubFloatToFloat(f float64, m int) float64 {
  134. newn := SubFloatToString(f, m)
  135. newf, _ := strconv.ParseFloat(newn, 64)
  136. return newf
  137. }
  138. //获取相差时间-年
  139. func GetYearDiffer(start_time, end_time string) int {
  140. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  141. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  142. age := t2.Year() - t1.Year()
  143. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  144. age--
  145. }
  146. return age
  147. }
  148. //获取相差时间-秒
  149. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  150. diff := end_time.Unix() - start_time.Unix()
  151. return diff
  152. }
  153. func FixFloat(f float64, m int) float64 {
  154. newn := SubFloatToString(f+0.00000001, m)
  155. newf, _ := strconv.ParseFloat(newn, 64)
  156. return newf
  157. }
  158. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  159. func StrListToString(strList []string) (str string) {
  160. if len(strList) > 0 {
  161. for k, v := range strList {
  162. if k == 0 {
  163. str = v
  164. } else {
  165. str = str + "," + v
  166. }
  167. }
  168. return
  169. }
  170. return ""
  171. }
  172. //Token
  173. func GetToken() string {
  174. randStr := GetRandString(64)
  175. token := MD5(randStr + Md5Key)
  176. tokenLen := 64 - len(token)
  177. return strings.ToUpper(token + GetRandString(tokenLen))
  178. }
  179. //数据没有记录
  180. func ErrNoRow() string {
  181. return "<QuerySeter> no row found"
  182. }
  183. //校验邮箱格式
  184. func ValidateEmailFormatat(email string) bool {
  185. reg := regexp.MustCompile(RegularEmail)
  186. return reg.MatchString(email)
  187. }
  188. //验证是否是手机号
  189. func ValidateMobileFormatat(mobileNum string) bool {
  190. reg := regexp.MustCompile(RegularMobile)
  191. return reg.MatchString(mobileNum)
  192. }
  193. //验证是否是固定电话
  194. func ValidateFixedTelephoneFormatat(mobileNum string) bool {
  195. reg := regexp.MustCompile(RegularFixedTelephone)
  196. return reg.MatchString(mobileNum)
  197. }
  198. //验证是否是固定电话宽松
  199. func ValidateFixedTelephoneFormatatEasy(mobileNum string) bool {
  200. reg := regexp.MustCompile(RegularFixedTelephoneEasy)
  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 GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  455. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  456. out, err := exec.Command("bash", "-c", cmd).Output()
  457. if err != nil {
  458. return
  459. }
  460. outTimes := string(out)
  461. fmt.Println("outTimes:", outTimes)
  462. if outTimes != "" {
  463. timeArr := strings.Split(outTimes, ":")
  464. h := timeArr[0]
  465. m := timeArr[1]
  466. s := timeArr[2]
  467. hInt, err := strconv.Atoi(h)
  468. if err != nil {
  469. return playSeconds, err
  470. }
  471. mInt, err := strconv.Atoi(m)
  472. if err != nil {
  473. return playSeconds, err
  474. }
  475. s = strings.Trim(s, " ")
  476. s = strings.Trim(s, "\n")
  477. sInt, err := strconv.ParseFloat(s, 64)
  478. if err != nil {
  479. return playSeconds, err
  480. }
  481. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  482. }
  483. return
  484. }
  485. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  486. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  487. tradeCode = strings.Trim(tradeCode, " ")
  488. tradeCodeInt, err := strconv.Atoi(tradeCode)
  489. if err != nil {
  490. return
  491. }
  492. tradeCodeInt = tradeCodeInt + 1
  493. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  494. return
  495. }
  496. // excel日期字段格式化 yyyy-mm-dd
  497. func ConvertToFormatDay(excelDaysString string) string {
  498. // 2006-01-02 距离 1900-01-01的天数
  499. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  500. curDiffDay := excelDaysString
  501. b, _ := strconv.Atoi(curDiffDay)
  502. // 获取excel的日期距离2006-01-02的天数
  503. realDiffDay := b - baseDiffDay
  504. //fmt.Println("realDiffDay:",realDiffDay)
  505. // 距离2006-01-02 秒数
  506. realDiffSecond := realDiffDay * 24 * 3600
  507. //fmt.Println("realDiffSecond:",realDiffSecond)
  508. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  509. baseOriginSecond := 1136185445
  510. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  511. return resultTime
  512. }
  513. //字符串转换为time
  514. func StrTimeToTime(strTime string) time.Time {
  515. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  516. loc, _ := time.LoadLocation("Local") //重要:获取时区
  517. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  518. return resultTime
  519. }
  520. //时间格式去掉时分秒
  521. func TimeRemoveHms(strTime string) string {
  522. var Ymd string
  523. var resultTime = StrTimeToTime(strTime)
  524. year := resultTime.Year()
  525. month := resultTime.Format("01")
  526. day1 := resultTime.Day()
  527. if day1 < 10 {
  528. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  529. } else {
  530. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  531. }
  532. return Ymd
  533. }
  534. //时间格式去掉时分秒
  535. func TimeRemoveHms2(strTime string) string {
  536. var Ymd string
  537. var resultTime = StrTimeToTime(strTime)
  538. year := resultTime.Year()
  539. month := resultTime.Format("01")
  540. day1 := resultTime.Day()
  541. if day1 < 10 {
  542. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  543. } else {
  544. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  545. }
  546. return Ymd
  547. }
  548. //判断时间是当年的第几周
  549. func WeekByDate(t time.Time) string {
  550. var resultSAtr string
  551. //t = t.AddDate(0, 0, -8) // 减少八天跟老数据标题统一
  552. yearDay := t.YearDay()
  553. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  554. firstDayInWeek := int(yearFirstDay.Weekday())
  555. //今年第一周有几天
  556. firstWeekDays := 1
  557. if firstDayInWeek != 0 {
  558. firstWeekDays = 7 - firstDayInWeek + 1
  559. }
  560. var week int
  561. if yearDay <= firstWeekDays {
  562. week = 1
  563. } else {
  564. week = (yearDay-firstWeekDays)/7 + 2
  565. }
  566. resultSAtr = "(" + strconv.Itoa(t.Year()) + "年第" + strconv.Itoa(week) + "周" + ")"
  567. return resultSAtr
  568. }
  569. func Mp3Time(videoPlaySeconds string) string {
  570. var d int
  571. var timeStr string
  572. a, _ := strconv.ParseFloat(videoPlaySeconds, 32)
  573. b := int(a)
  574. if b <= 60 {
  575. timeStr = "00:" + strconv.Itoa(b)
  576. } else {
  577. c := b % 60
  578. d = b / 60
  579. if d < 10 {
  580. timeStr = "0" + strconv.Itoa(d) + ":" + strconv.Itoa(c)
  581. } else {
  582. timeStr = strconv.Itoa(d) + ":" + strconv.Itoa(c)
  583. }
  584. }
  585. return timeStr
  586. }
  587. //用户参会时间转换
  588. func GetAttendanceDetailSeconds(secondNum int) string {
  589. var timeStr string
  590. if secondNum <= 60 {
  591. if secondNum < 10 {
  592. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  593. } else {
  594. timeStr = strconv.Itoa(secondNum) + "''"
  595. }
  596. } else {
  597. var remainderStr string
  598. remainderNum := secondNum % 60
  599. minuteNum := secondNum / 60
  600. if remainderNum < 10 {
  601. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  602. } else {
  603. remainderStr = strconv.Itoa(remainderNum) + "''"
  604. }
  605. if minuteNum < 10 {
  606. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  607. } else {
  608. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  609. }
  610. }
  611. return timeStr
  612. }