common.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. //md5加密
  64. func Get16MD5Encode(data string) string {
  65. m := md5.Sum([]byte(data))
  66. encodehex := hex.EncodeToString(m[:])
  67. return encodehex[8:24]
  68. }
  69. // 获取数字随机字符
  70. func GetRandDigit(n int) string {
  71. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  72. }
  73. // 获取随机数
  74. func GetRandNumber(n int) int {
  75. return rnd.Intn(n)
  76. }
  77. func GetRandInt(min, max int) int {
  78. if min >= max || min == 0 || max == 0 {
  79. return max
  80. }
  81. return rand.Intn(max-min) + min
  82. }
  83. func GetToday(format string) string {
  84. today := time.Now().Format(format)
  85. return today
  86. }
  87. //获取今天剩余秒数
  88. func GetTodayLastSecond() time.Duration {
  89. today := GetToday(FormatDate) + " 23:59:59"
  90. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  91. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  92. }
  93. // 处理出生日期函数
  94. func GetBrithDate(idcard string) string {
  95. l := len(idcard)
  96. var s string
  97. if l == 15 {
  98. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  99. return s
  100. }
  101. if l == 18 {
  102. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  103. return s
  104. }
  105. return GetToday(FormatDate)
  106. }
  107. //处理性别
  108. func WhichSexByIdcard(idcard string) string {
  109. var sexs = [2]string{"女", "男"}
  110. length := len(idcard)
  111. if length == 18 {
  112. sex, _ := strconv.Atoi(string(idcard[16]))
  113. return sexs[sex%2]
  114. } else if length == 15 {
  115. sex, _ := strconv.Atoi(string(idcard[14]))
  116. return sexs[sex%2]
  117. }
  118. return "男"
  119. }
  120. //截取小数点后几位
  121. func SubFloatToString(f float64, m int) string {
  122. n := strconv.FormatFloat(f, 'f', -1, 64)
  123. if n == "" {
  124. return ""
  125. }
  126. if m >= len(n) {
  127. return n
  128. }
  129. newn := strings.Split(n, ".")
  130. if m == 0 {
  131. return newn[0]
  132. }
  133. if len(newn) < 2 || m >= len(newn[1]) {
  134. return n
  135. }
  136. return newn[0] + "." + newn[1][:m]
  137. }
  138. //截取小数点后几位
  139. func SubFloatToFloat(f float64, m int) float64 {
  140. newn := SubFloatToString(f, m)
  141. newf, _ := strconv.ParseFloat(newn, 64)
  142. return newf
  143. }
  144. //获取相差时间-年
  145. func GetYearDiffer(start_time, end_time string) int {
  146. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  147. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  148. age := t2.Year() - t1.Year()
  149. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  150. age--
  151. }
  152. return age
  153. }
  154. //获取相差时间-秒
  155. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  156. diff := end_time.Unix() - start_time.Unix()
  157. return diff
  158. }
  159. func FixFloat(f float64, m int) float64 {
  160. newn := SubFloatToString(f+0.00000001, m)
  161. newf, _ := strconv.ParseFloat(newn, 64)
  162. return newf
  163. }
  164. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  165. func StrListToString(strList []string) (str string) {
  166. if len(strList) > 0 {
  167. for k, v := range strList {
  168. if k == 0 {
  169. str = v
  170. } else {
  171. str = str + "," + v
  172. }
  173. }
  174. return
  175. }
  176. return ""
  177. }
  178. //Token
  179. func GetToken() string {
  180. randStr := GetRandString(64)
  181. token := MD5(randStr + Md5Key)
  182. tokenLen := 64 - len(token)
  183. return strings.ToUpper(token + GetRandString(tokenLen))
  184. }
  185. //数据没有记录
  186. func ErrNoRow() string {
  187. return "<QuerySeter> no row found"
  188. }
  189. //校验邮箱格式
  190. func ValidateEmailFormatat(email string) bool {
  191. reg := regexp.MustCompile(RegularEmail)
  192. return reg.MatchString(email)
  193. }
  194. //验证是否是手机号
  195. func ValidateMobileFormatat(mobileNum string) bool {
  196. reg := regexp.MustCompile(RegularMobile)
  197. return reg.MatchString(mobileNum)
  198. }
  199. //验证是否是固定电话
  200. func ValidateFixedTelephoneFormatat(mobileNum string) bool {
  201. reg := regexp.MustCompile(RegularFixedTelephone)
  202. return reg.MatchString(mobileNum)
  203. }
  204. //验证是否是固定电话宽松
  205. func ValidateFixedTelephoneFormatatEasy(mobileNum string) bool {
  206. reg := regexp.MustCompile(RegularFixedTelephoneEasy)
  207. return reg.MatchString(mobileNum)
  208. }
  209. //判断文件是否存在
  210. func FileIsExist(filePath string) bool {
  211. _, err := os.Stat(filePath)
  212. return err == nil || os.IsExist(err)
  213. }
  214. //获取图片扩展名
  215. func GetImgExt(file string) (ext string, err error) {
  216. var headerByte []byte
  217. headerByte = make([]byte, 8)
  218. fd, err := os.Open(file)
  219. if err != nil {
  220. return "", err
  221. }
  222. defer fd.Close()
  223. _, err = fd.Read(headerByte)
  224. if err != nil {
  225. return "", err
  226. }
  227. xStr := fmt.Sprintf("%x", headerByte)
  228. switch {
  229. case xStr == "89504e470d0a1a0a":
  230. ext = ".png"
  231. case xStr == "0000010001002020":
  232. ext = ".ico"
  233. case xStr == "0000020001002020":
  234. ext = ".cur"
  235. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  236. ext = ".gif"
  237. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  238. ext = ".tga"
  239. case xStr[:8] == "464f524d":
  240. ext = ".iff"
  241. case xStr[:8] == "52494646":
  242. ext = ".ani"
  243. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  244. ext = ".tiff"
  245. case xStr[:4] == "424d":
  246. ext = ".bmp"
  247. case xStr[:4] == "ffd8":
  248. ext = ".jpg"
  249. case xStr[:2] == "0a":
  250. ext = ".pcx"
  251. default:
  252. ext = ""
  253. }
  254. return ext, nil
  255. }
  256. //保存图片
  257. func SaveImage(path string, img image.Image) (err error) {
  258. //需要保持的文件
  259. imgfile, err := os.Create(path)
  260. defer imgfile.Close()
  261. // 以PNG格式保存文件
  262. err = png.Encode(imgfile, img)
  263. return err
  264. }
  265. //保存base64数据为文件
  266. func SaveBase64ToFile(content, path string) error {
  267. data, err := base64.StdEncoding.DecodeString(content)
  268. if err != nil {
  269. return err
  270. }
  271. f, err := os.Create(path)
  272. defer f.Close()
  273. if err != nil {
  274. return err
  275. }
  276. f.Write(data)
  277. return nil
  278. }
  279. func SaveBase64ToFileBySeek(content, path string) (err error) {
  280. data, err := base64.StdEncoding.DecodeString(content)
  281. exist, err := PathExists(path)
  282. if err != nil {
  283. return
  284. }
  285. if !exist {
  286. f, err := os.Create(path)
  287. if err != nil {
  288. return err
  289. }
  290. n, _ := f.Seek(0, 2)
  291. // 从末尾的偏移量开始写入内容
  292. _, err = f.WriteAt([]byte(data), n)
  293. defer f.Close()
  294. } else {
  295. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  296. if err != nil {
  297. return err
  298. }
  299. n, _ := f.Seek(0, 2)
  300. // 从末尾的偏移量开始写入内容
  301. _, err = f.WriteAt([]byte(data), n)
  302. defer f.Close()
  303. }
  304. return nil
  305. }
  306. func PathExists(path string) (bool, error) {
  307. _, err := os.Stat(path)
  308. if err == nil {
  309. return true, nil
  310. }
  311. if os.IsNotExist(err) {
  312. return false, nil
  313. }
  314. return false, err
  315. }
  316. func StartIndex(page, pagesize int) int {
  317. if page > 1 {
  318. return (page - 1) * pagesize
  319. }
  320. return 0
  321. }
  322. func PageCount(count, pagesize int) int {
  323. if count%pagesize > 0 {
  324. return count/pagesize + 1
  325. } else {
  326. return count / pagesize
  327. }
  328. }
  329. func TrimHtml(src string) string {
  330. //将HTML标签全转换成小写
  331. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  332. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  333. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  334. src = re.ReplaceAllString(src, "[图片]")
  335. re, _ = regexp.Compile("class[\\S\\s]+?>")
  336. src = re.ReplaceAllString(src, "")
  337. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  338. src = re.ReplaceAllString(src, "")
  339. return strings.TrimSpace(src)
  340. }
  341. //1556164246 -> 2019-04-25 03:50:46 +0000
  342. //timestamp
  343. func TimeToTimestamp() {
  344. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  345. }
  346. func ToUnicode(text string) string {
  347. textQuoted := strconv.QuoteToASCII(text)
  348. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  349. return textUnquoted
  350. }
  351. func VersionToInt(version string) int {
  352. version = strings.Replace(version, ".", "", -1)
  353. n, _ := strconv.Atoi(version)
  354. return n
  355. }
  356. func IsCheckInList(list []int, s int) bool {
  357. for _, v := range list {
  358. if v == s {
  359. return true
  360. }
  361. }
  362. return false
  363. }
  364. func round(num float64) int {
  365. return int(num + math.Copysign(0.5, num))
  366. }
  367. func toFixed(num float64, precision int) float64 {
  368. output := math.Pow(10, float64(precision))
  369. return float64(round(num*output)) / output
  370. }
  371. // GetWilsonScore returns Wilson Score
  372. func GetWilsonScore(p, n float64) float64 {
  373. if p == 0 && n == 0 {
  374. return 0
  375. }
  376. 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)
  377. }
  378. //将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  379. func ChangeWordsToNum(str string) (numStr string) {
  380. words := ([]rune)(str)
  381. num := 0
  382. n := 0
  383. for i := 0; i < len(words); i++ {
  384. word := string(words[i : i+1])
  385. switch word {
  386. case "万":
  387. if n == 0 {
  388. n = 1
  389. }
  390. n = n * 10000
  391. num = num*10000 + n
  392. n = 0
  393. case "千":
  394. if n == 0 {
  395. n = 1
  396. }
  397. n = n * 1000
  398. num += n
  399. n = 0
  400. case "百":
  401. if n == 0 {
  402. n = 1
  403. }
  404. n = n * 100
  405. num += n
  406. n = 0
  407. case "十":
  408. if n == 0 {
  409. n = 1
  410. }
  411. n = n * 10
  412. num += n
  413. n = 0
  414. case "一":
  415. n += 1
  416. case "二":
  417. n += 2
  418. case "三":
  419. n += 3
  420. case "四":
  421. n += 4
  422. case "五":
  423. n += 5
  424. case "六":
  425. n += 6
  426. case "七":
  427. n += 7
  428. case "八":
  429. n += 8
  430. case "九":
  431. n += 9
  432. case "零":
  433. default:
  434. if n > 0 {
  435. num += n
  436. n = 0
  437. }
  438. if num == 0 {
  439. numStr += word
  440. } else {
  441. numStr += strconv.Itoa(num) + word
  442. num = 0
  443. }
  444. }
  445. }
  446. if n > 0 {
  447. num += n
  448. n = 0
  449. }
  450. if num != 0 {
  451. numStr += strconv.Itoa(num)
  452. }
  453. return
  454. }
  455. func Sha1(data string) string {
  456. sha1 := sha1.New()
  457. sha1.Write([]byte(data))
  458. return hex.EncodeToString(sha1.Sum([]byte("")))
  459. }
  460. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  461. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  462. out, err := exec.Command("bash", "-c", cmd).Output()
  463. if err != nil {
  464. return
  465. }
  466. outTimes := string(out)
  467. fmt.Println("outTimes:", outTimes)
  468. if outTimes != "" {
  469. timeArr := strings.Split(outTimes, ":")
  470. h := timeArr[0]
  471. m := timeArr[1]
  472. s := timeArr[2]
  473. hInt, err := strconv.Atoi(h)
  474. if err != nil {
  475. return playSeconds, err
  476. }
  477. mInt, err := strconv.Atoi(m)
  478. if err != nil {
  479. return playSeconds, err
  480. }
  481. s = strings.Trim(s, " ")
  482. s = strings.Trim(s, "\n")
  483. sInt, err := strconv.ParseFloat(s, 64)
  484. if err != nil {
  485. return playSeconds, err
  486. }
  487. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  488. }
  489. return
  490. }
  491. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  492. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  493. tradeCode = strings.Trim(tradeCode, " ")
  494. tradeCodeInt, err := strconv.Atoi(tradeCode)
  495. if err != nil {
  496. return
  497. }
  498. tradeCodeInt = tradeCodeInt + 1
  499. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  500. return
  501. }
  502. // excel日期字段格式化 yyyy-mm-dd
  503. func ConvertToFormatDay(excelDaysString string) string {
  504. // 2006-01-02 距离 1900-01-01的天数
  505. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  506. curDiffDay := excelDaysString
  507. b, _ := strconv.Atoi(curDiffDay)
  508. // 获取excel的日期距离2006-01-02的天数
  509. realDiffDay := b - baseDiffDay
  510. //fmt.Println("realDiffDay:",realDiffDay)
  511. // 距离2006-01-02 秒数
  512. realDiffSecond := realDiffDay * 24 * 3600
  513. //fmt.Println("realDiffSecond:",realDiffSecond)
  514. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  515. baseOriginSecond := 1136185445
  516. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  517. return resultTime
  518. }
  519. //字符串转换为time
  520. func StrTimeToTime(strTime string) time.Time {
  521. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  522. loc, _ := time.LoadLocation("Local") //重要:获取时区
  523. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  524. return resultTime
  525. }
  526. //时间格式去掉时分秒
  527. func TimeRemoveHms(strTime string) string {
  528. var Ymd string
  529. var resultTime = StrTimeToTime(strTime)
  530. year := resultTime.Year()
  531. month := resultTime.Format("01")
  532. day1 := resultTime.Day()
  533. if day1 < 10 {
  534. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  535. } else {
  536. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  537. }
  538. return Ymd
  539. }
  540. //时间格式去掉时分秒
  541. func TimeRemoveHms2(strTime string) string {
  542. var Ymd string
  543. var resultTime = StrTimeToTime(strTime)
  544. year := resultTime.Year()
  545. month := resultTime.Format("01")
  546. day1 := resultTime.Day()
  547. if day1 < 10 {
  548. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  549. } else {
  550. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  551. }
  552. return Ymd
  553. }
  554. //判断时间是当年的第几周
  555. func WeekByDate(t time.Time) string {
  556. var resultSAtr string
  557. //t = t.AddDate(0, 0, -8) // 减少八天跟老数据标题统一
  558. yearDay := t.YearDay()
  559. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  560. firstDayInWeek := int(yearFirstDay.Weekday())
  561. //今年第一周有几天
  562. firstWeekDays := 1
  563. if firstDayInWeek != 0 {
  564. firstWeekDays = 7 - firstDayInWeek + 1
  565. }
  566. var week int
  567. if yearDay <= firstWeekDays {
  568. week = 1
  569. } else {
  570. week = (yearDay-firstWeekDays)/7 + 2
  571. }
  572. resultSAtr = "(" + strconv.Itoa(t.Year()) + "年第" + strconv.Itoa(week) + "周" + ")"
  573. return resultSAtr
  574. }
  575. func Mp3Time(videoPlaySeconds string) string {
  576. var d int
  577. var timeStr string
  578. a, _ := strconv.ParseFloat(videoPlaySeconds, 32)
  579. b := int(a)
  580. if b <= 60 {
  581. timeStr = "00:" + strconv.Itoa(b)
  582. } else {
  583. c := b % 60
  584. d = b / 60
  585. if d < 10 {
  586. timeStr = "0" + strconv.Itoa(d) + ":" + strconv.Itoa(c)
  587. } else {
  588. timeStr = strconv.Itoa(d) + ":" + strconv.Itoa(c)
  589. }
  590. }
  591. return timeStr
  592. }
  593. //用户参会时间转换
  594. func GetAttendanceDetailSeconds(secondNum int) string {
  595. var timeStr string
  596. if secondNum <= 60 {
  597. if secondNum < 10 {
  598. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  599. } else {
  600. timeStr = strconv.Itoa(secondNum) + "''"
  601. }
  602. } else {
  603. var remainderStr string
  604. remainderNum := secondNum % 60
  605. minuteNum := secondNum / 60
  606. if remainderNum < 10 {
  607. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  608. } else {
  609. remainderStr = strconv.Itoa(remainderNum) + "''"
  610. }
  611. if minuteNum < 10 {
  612. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  613. } else {
  614. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  615. }
  616. }
  617. return timeStr
  618. }