common.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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 SubFloatToFloatStr(f float64, m int) string {
  140. newn := SubFloatToString(f, m)
  141. return newn
  142. }
  143. //获取相差时间-年
  144. func GetYearDiffer(start_time, end_time string) int {
  145. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  146. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  147. age := t2.Year() - t1.Year()
  148. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  149. age--
  150. }
  151. return age
  152. }
  153. //获取相差时间-秒
  154. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  155. diff := end_time.Unix() - start_time.Unix()
  156. return diff
  157. }
  158. func FixFloat(f float64, m int) float64 {
  159. newn := SubFloatToString(f+0.00000001, m)
  160. newf, _ := strconv.ParseFloat(newn, 64)
  161. return newf
  162. }
  163. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  164. func StrListToString(strList []string) (str string) {
  165. if len(strList) > 0 {
  166. for k, v := range strList {
  167. if k == 0 {
  168. str = v
  169. } else {
  170. str = str + "," + v
  171. }
  172. }
  173. return
  174. }
  175. return ""
  176. }
  177. //Token
  178. func GetToken() string {
  179. randStr := GetRandString(64)
  180. token := MD5(randStr + Md5Key)
  181. tokenLen := 64 - len(token)
  182. return strings.ToUpper(token + GetRandString(tokenLen))
  183. }
  184. //数据没有记录
  185. func ErrNoRow() string {
  186. return "<QuerySeter> no row found"
  187. }
  188. //判断文件是否存在
  189. func FileIsExist(filePath string) bool {
  190. _, err := os.Stat(filePath)
  191. return err == nil || os.IsExist(err)
  192. }
  193. //获取图片扩展名
  194. func GetImgExt(file string) (ext string, err error) {
  195. var headerByte []byte
  196. headerByte = make([]byte, 8)
  197. fd, err := os.Open(file)
  198. if err != nil {
  199. return "", err
  200. }
  201. defer fd.Close()
  202. _, err = fd.Read(headerByte)
  203. if err != nil {
  204. return "", err
  205. }
  206. xStr := fmt.Sprintf("%x", headerByte)
  207. switch {
  208. case xStr == "89504e470d0a1a0a":
  209. ext = ".png"
  210. case xStr == "0000010001002020":
  211. ext = ".ico"
  212. case xStr == "0000020001002020":
  213. ext = ".cur"
  214. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  215. ext = ".gif"
  216. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  217. ext = ".tga"
  218. case xStr[:8] == "464f524d":
  219. ext = ".iff"
  220. case xStr[:8] == "52494646":
  221. ext = ".ani"
  222. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  223. ext = ".tiff"
  224. case xStr[:4] == "424d":
  225. ext = ".bmp"
  226. case xStr[:4] == "ffd8":
  227. ext = ".jpg"
  228. case xStr[:2] == "0a":
  229. ext = ".pcx"
  230. default:
  231. ext = ""
  232. }
  233. return ext, nil
  234. }
  235. //保存图片
  236. func SaveImage(path string, img image.Image) (err error) {
  237. //需要保持的文件
  238. imgfile, err := os.Create(path)
  239. defer imgfile.Close()
  240. // 以PNG格式保存文件
  241. err = png.Encode(imgfile, img)
  242. return err
  243. }
  244. //保存base64数据为文件
  245. func SaveBase64ToFile(content, path string) error {
  246. data, err := base64.StdEncoding.DecodeString(content)
  247. if err != nil {
  248. return err
  249. }
  250. f, err := os.Create(path)
  251. defer f.Close()
  252. if err != nil {
  253. return err
  254. }
  255. f.Write(data)
  256. return nil
  257. }
  258. func SaveBase64ToFileBySeek(content, path string) (err error) {
  259. data, err := base64.StdEncoding.DecodeString(content)
  260. exist, err := PathExists(path)
  261. if err != nil {
  262. return
  263. }
  264. if !exist {
  265. f, err := os.Create(path)
  266. if err != nil {
  267. return err
  268. }
  269. n, _ := f.Seek(0, 2)
  270. // 从末尾的偏移量开始写入内容
  271. _, err = f.WriteAt([]byte(data), n)
  272. defer f.Close()
  273. } else {
  274. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  275. if err != nil {
  276. return err
  277. }
  278. n, _ := f.Seek(0, 2)
  279. // 从末尾的偏移量开始写入内容
  280. _, err = f.WriteAt([]byte(data), n)
  281. defer f.Close()
  282. }
  283. return nil
  284. }
  285. func PathExists(path string) (bool, error) {
  286. _, err := os.Stat(path)
  287. if err == nil {
  288. return true, nil
  289. }
  290. if os.IsNotExist(err) {
  291. return false, nil
  292. }
  293. return false, err
  294. }
  295. func StartIndex(page, pagesize int) int {
  296. if page > 1 {
  297. return (page - 1) * pagesize
  298. }
  299. return 0
  300. }
  301. func PageCount(count, pagesize int) int {
  302. if count%pagesize > 0 {
  303. return count/pagesize + 1
  304. } else {
  305. return count / pagesize
  306. }
  307. }
  308. func TrimHtml(src string) string {
  309. //将HTML标签全转换成小写
  310. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  311. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  312. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  313. src = re.ReplaceAllString(src, "[图片]")
  314. re, _ = regexp.Compile("class[\\S\\s]+?>")
  315. src = re.ReplaceAllString(src, "")
  316. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  317. src = re.ReplaceAllString(src, "")
  318. return strings.TrimSpace(src)
  319. }
  320. //1556164246 -> 2019-04-25 03:50:46 +0000
  321. //timestamp
  322. func TimeToTimestamp() {
  323. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  324. }
  325. func ToUnicode(text string) string {
  326. textQuoted := strconv.QuoteToASCII(text)
  327. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  328. return textUnquoted
  329. }
  330. func VersionToInt(version string) int {
  331. version = strings.Replace(version, ".", "", -1)
  332. n, _ := strconv.Atoi(version)
  333. return n
  334. }
  335. func IsCheckInList(list []int, s int) bool {
  336. for _, v := range list {
  337. if v == s {
  338. return true
  339. }
  340. }
  341. return false
  342. }
  343. func round(num float64) int {
  344. return int(num + math.Copysign(0.5, num))
  345. }
  346. func toFixed(num float64, precision int) float64 {
  347. output := math.Pow(10, float64(precision))
  348. return float64(round(num*output)) / output
  349. }
  350. // GetWilsonScore returns Wilson Score
  351. func GetWilsonScore(p, n float64) float64 {
  352. if p == 0 && n == 0 {
  353. return 0
  354. }
  355. 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)
  356. }
  357. //将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  358. func ChangeWordsToNum(str string) (numStr string) {
  359. words := ([]rune)(str)
  360. num := 0
  361. n := 0
  362. for i := 0; i < len(words); i++ {
  363. word := string(words[i : i+1])
  364. switch word {
  365. case "万":
  366. if n == 0 {
  367. n = 1
  368. }
  369. n = n * 10000
  370. num = num*10000 + n
  371. n = 0
  372. case "千":
  373. if n == 0 {
  374. n = 1
  375. }
  376. n = n * 1000
  377. num += n
  378. n = 0
  379. case "百":
  380. if n == 0 {
  381. n = 1
  382. }
  383. n = n * 100
  384. num += n
  385. n = 0
  386. case "十":
  387. if n == 0 {
  388. n = 1
  389. }
  390. n = n * 10
  391. num += n
  392. n = 0
  393. case "一":
  394. n += 1
  395. case "二":
  396. n += 2
  397. case "三":
  398. n += 3
  399. case "四":
  400. n += 4
  401. case "五":
  402. n += 5
  403. case "六":
  404. n += 6
  405. case "七":
  406. n += 7
  407. case "八":
  408. n += 8
  409. case "九":
  410. n += 9
  411. case "零":
  412. default:
  413. if n > 0 {
  414. num += n
  415. n = 0
  416. }
  417. if num == 0 {
  418. numStr += word
  419. } else {
  420. numStr += strconv.Itoa(num) + word
  421. num = 0
  422. }
  423. }
  424. }
  425. if n > 0 {
  426. num += n
  427. n = 0
  428. }
  429. if num != 0 {
  430. numStr += strconv.Itoa(num)
  431. }
  432. return
  433. }
  434. func Sha1(data string) string {
  435. sha1 := sha1.New()
  436. sha1.Write([]byte(data))
  437. return hex.EncodeToString(sha1.Sum([]byte("")))
  438. }
  439. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  440. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  441. out, err := exec.Command("bash", "-c", cmd).Output()
  442. if err != nil {
  443. return
  444. }
  445. outTimes := string(out)
  446. fmt.Println("outTimes:", outTimes)
  447. if outTimes != "" {
  448. timeArr := strings.Split(outTimes, ":")
  449. h := timeArr[0]
  450. m := timeArr[1]
  451. s := timeArr[2]
  452. hInt, err := strconv.Atoi(h)
  453. if err != nil {
  454. return playSeconds, err
  455. }
  456. mInt, err := strconv.Atoi(m)
  457. if err != nil {
  458. return playSeconds, err
  459. }
  460. s = strings.Trim(s, " ")
  461. s = strings.Trim(s, "\n")
  462. sInt, err := strconv.ParseFloat(s, 64)
  463. if err != nil {
  464. return playSeconds, err
  465. }
  466. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  467. }
  468. return
  469. }
  470. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  471. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  472. tradeCode = strings.Trim(tradeCode, " ")
  473. tradeCodeInt, err := strconv.Atoi(tradeCode)
  474. if err != nil {
  475. return
  476. }
  477. tradeCodeInt = tradeCodeInt + 1
  478. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  479. return
  480. }
  481. // excel日期字段格式化 yyyy-mm-dd
  482. func ConvertToFormatDay(excelDaysString string) string {
  483. // 2006-01-02 距离 1900-01-01的天数
  484. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  485. curDiffDay := excelDaysString
  486. b, _ := strconv.Atoi(curDiffDay)
  487. // 获取excel的日期距离2006-01-02的天数
  488. realDiffDay := b - baseDiffDay
  489. //fmt.Println("realDiffDay:",realDiffDay)
  490. // 距离2006-01-02 秒数
  491. realDiffSecond := realDiffDay * 24 * 3600
  492. //fmt.Println("realDiffSecond:",realDiffSecond)
  493. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  494. baseOriginSecond := 1136185445
  495. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  496. return resultTime
  497. }
  498. func CheckPwd(pwd string) bool {
  499. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  500. reg := regexp.MustCompile(compile)
  501. flag := reg.MatchString(pwd)
  502. return flag
  503. }
  504. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  505. // 数字月份必须前置补零
  506. if len(myMonth) == 1 {
  507. myMonth = "0" + myMonth
  508. }
  509. yInt, _ := strconv.Atoi(myYear)
  510. timeLayout := "2006-01-02 15:04:05"
  511. loc, _ := time.LoadLocation("Local")
  512. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  513. newMonth := theTime.Month()
  514. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  515. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  516. return t1, t2
  517. }
  518. //移除字符串中的空格
  519. func TrimStr(str string) (str2 string) {
  520. return strings.Replace(str, " ", "", -1)
  521. }
  522. //字符串转换为time
  523. func StrTimeToTime(strTime string) time.Time {
  524. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  525. loc, _ := time.LoadLocation("Local") //重要:获取时区
  526. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  527. return resultTime
  528. }
  529. //字符串类型时间转周几
  530. func StrDateTimeToWeek(strTime string) string {
  531. var WeekDayMap = map[string]string{
  532. "Monday": "周一",
  533. "Tuesday": "周二",
  534. "Wednesday": "周三",
  535. "Thursday": "周四",
  536. "Friday": "周五",
  537. "Saturday": "周六",
  538. "Sunday": "周日",
  539. }
  540. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  541. startday, _ := time.Parse("2006-01-02", ctime)
  542. staweek_int := startday.Weekday().String()
  543. return WeekDayMap[staweek_int]
  544. }
  545. //时间格式转年月日字符串
  546. func TimeToStrYmd(time2 time.Time) string {
  547. var Ymd string
  548. year := time2.Year()
  549. month := time2.Format("1")
  550. day1 := time.Now().Day()
  551. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  552. return Ymd
  553. }
  554. //时间格式去掉时分秒
  555. func TimeRemoveHms(strTime string) string {
  556. var Ymd string
  557. var resultTime = StrTimeToTime(strTime)
  558. year := resultTime.Year()
  559. month := resultTime.Format("01")
  560. day1 := time.Now().Day()
  561. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  562. return Ymd
  563. }
  564. //文章上一次编辑时间
  565. func ArticleLastTime(strTime string) string {
  566. var newTime string
  567. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  568. diffTime := time.Now().Unix() - stamp.Unix()
  569. if diffTime <= 60 {
  570. newTime = "当前"
  571. } else if diffTime < 60*60 {
  572. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  573. } else if diffTime < 24*60*60 {
  574. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  575. } else if diffTime < 30*24*60*60 {
  576. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  577. } else if diffTime < 12*30*24*60*60 {
  578. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  579. } else {
  580. newTime = "1年前"
  581. }
  582. return newTime
  583. }