common.go 15 KB

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