common.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 FileIsExist(filePath string) bool {
  196. _, err := os.Stat(filePath)
  197. return err == nil || os.IsExist(err)
  198. }
  199. // 获取图片扩展名
  200. func GetImgExt(file string) (ext string, err error) {
  201. var headerByte []byte
  202. headerByte = make([]byte, 8)
  203. fd, err := os.Open(file)
  204. if err != nil {
  205. return "", err
  206. }
  207. defer fd.Close()
  208. _, err = fd.Read(headerByte)
  209. if err != nil {
  210. return "", err
  211. }
  212. xStr := fmt.Sprintf("%x", headerByte)
  213. switch {
  214. case xStr == "89504e470d0a1a0a":
  215. ext = ".png"
  216. case xStr == "0000010001002020":
  217. ext = ".ico"
  218. case xStr == "0000020001002020":
  219. ext = ".cur"
  220. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  221. ext = ".gif"
  222. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  223. ext = ".tga"
  224. case xStr[:8] == "464f524d":
  225. ext = ".iff"
  226. case xStr[:8] == "52494646":
  227. ext = ".ani"
  228. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  229. ext = ".tiff"
  230. case xStr[:4] == "424d":
  231. ext = ".bmp"
  232. case xStr[:4] == "ffd8":
  233. ext = ".jpg"
  234. case xStr[:2] == "0a":
  235. ext = ".pcx"
  236. default:
  237. ext = ""
  238. }
  239. return ext, nil
  240. }
  241. // 保存图片
  242. func SaveImage(path string, img image.Image) (err error) {
  243. //需要保持的文件
  244. imgfile, err := os.Create(path)
  245. defer imgfile.Close()
  246. // 以PNG格式保存文件
  247. err = png.Encode(imgfile, img)
  248. return err
  249. }
  250. // 保存base64数据为文件
  251. func SaveBase64ToFile(content, path string) error {
  252. data, err := base64.StdEncoding.DecodeString(content)
  253. if err != nil {
  254. return err
  255. }
  256. f, err := os.Create(path)
  257. defer f.Close()
  258. if err != nil {
  259. return err
  260. }
  261. f.Write(data)
  262. return nil
  263. }
  264. func SaveBase64ToFileBySeek(content, path string) (err error) {
  265. data, err := base64.StdEncoding.DecodeString(content)
  266. exist, err := PathExists(path)
  267. if err != nil {
  268. return
  269. }
  270. if !exist {
  271. f, err := os.Create(path)
  272. if err != nil {
  273. return err
  274. }
  275. n, _ := f.Seek(0, 2)
  276. // 从末尾的偏移量开始写入内容
  277. _, err = f.WriteAt([]byte(data), n)
  278. defer f.Close()
  279. } else {
  280. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  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. }
  289. return nil
  290. }
  291. func PathExists(path string) (bool, error) {
  292. _, err := os.Stat(path)
  293. if err == nil {
  294. return true, nil
  295. }
  296. if os.IsNotExist(err) {
  297. return false, nil
  298. }
  299. return false, err
  300. }
  301. func StartIndex(page, pagesize int) int {
  302. if page > 1 {
  303. return (page - 1) * pagesize
  304. }
  305. return 0
  306. }
  307. func PageCount(count, pagesize int) int {
  308. if count%pagesize > 0 {
  309. return count/pagesize + 1
  310. } else {
  311. return count / pagesize
  312. }
  313. }
  314. func TrimHtml(src string) string {
  315. //将HTML标签全转换成小写
  316. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  317. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  318. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  319. src = re.ReplaceAllString(src, "[图片]")
  320. re, _ = regexp.Compile("class[\\S\\s]+?>")
  321. src = re.ReplaceAllString(src, "")
  322. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  323. src = re.ReplaceAllString(src, "")
  324. return strings.TrimSpace(src)
  325. }
  326. //1556164246 -> 2019-04-25 03:50:46 +0000
  327. //timestamp
  328. func TimeToTimestamp() {
  329. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  330. }
  331. func ToUnicode(text string) string {
  332. textQuoted := strconv.QuoteToASCII(text)
  333. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  334. return textUnquoted
  335. }
  336. func VersionToInt(version string) int {
  337. version = strings.Replace(version, ".", "", -1)
  338. n, _ := strconv.Atoi(version)
  339. return n
  340. }
  341. func IsCheckInList(list []int, s int) bool {
  342. for _, v := range list {
  343. if v == s {
  344. return true
  345. }
  346. }
  347. return false
  348. }
  349. func round(num float64) int {
  350. return int(num + math.Copysign(0.5, num))
  351. }
  352. func toFixed(num float64, precision int) float64 {
  353. output := math.Pow(10, float64(precision))
  354. return float64(round(num*output)) / output
  355. }
  356. // GetWilsonScore returns Wilson Score
  357. func GetWilsonScore(p, n float64) float64 {
  358. if p == 0 && n == 0 {
  359. return 0
  360. }
  361. 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)
  362. }
  363. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  364. func ChangeWordsToNum(str string) (numStr string) {
  365. words := ([]rune)(str)
  366. num := 0
  367. n := 0
  368. for i := 0; i < len(words); i++ {
  369. word := string(words[i : i+1])
  370. switch word {
  371. case "万":
  372. if n == 0 {
  373. n = 1
  374. }
  375. n = n * 10000
  376. num = num*10000 + n
  377. n = 0
  378. case "千":
  379. if n == 0 {
  380. n = 1
  381. }
  382. n = n * 1000
  383. num += n
  384. n = 0
  385. case "百":
  386. if n == 0 {
  387. n = 1
  388. }
  389. n = n * 100
  390. num += n
  391. n = 0
  392. case "十":
  393. if n == 0 {
  394. n = 1
  395. }
  396. n = n * 10
  397. num += n
  398. n = 0
  399. case "一":
  400. n += 1
  401. case "二":
  402. n += 2
  403. case "三":
  404. n += 3
  405. case "四":
  406. n += 4
  407. case "五":
  408. n += 5
  409. case "六":
  410. n += 6
  411. case "七":
  412. n += 7
  413. case "八":
  414. n += 8
  415. case "九":
  416. n += 9
  417. case "零":
  418. default:
  419. if n > 0 {
  420. num += n
  421. n = 0
  422. }
  423. if num == 0 {
  424. numStr += word
  425. } else {
  426. numStr += strconv.Itoa(num) + word
  427. num = 0
  428. }
  429. }
  430. }
  431. if n > 0 {
  432. num += n
  433. n = 0
  434. }
  435. if num != 0 {
  436. numStr += strconv.Itoa(num)
  437. }
  438. return
  439. }
  440. func Sha1(data string) string {
  441. sha1 := sha1.New()
  442. sha1.Write([]byte(data))
  443. return hex.EncodeToString(sha1.Sum([]byte("")))
  444. }
  445. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  446. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  447. out, err := exec.Command("bash", "-c", cmd).Output()
  448. if err != nil {
  449. return
  450. }
  451. outTimes := string(out)
  452. fmt.Println("outTimes:", outTimes)
  453. if outTimes != "" {
  454. timeArr := strings.Split(outTimes, ":")
  455. h := timeArr[0]
  456. m := timeArr[1]
  457. s := timeArr[2]
  458. hInt, err := strconv.Atoi(h)
  459. if err != nil {
  460. return playSeconds, err
  461. }
  462. mInt, err := strconv.Atoi(m)
  463. if err != nil {
  464. return playSeconds, err
  465. }
  466. s = strings.Trim(s, " ")
  467. s = strings.Trim(s, "\n")
  468. sInt, err := strconv.ParseFloat(s, 64)
  469. if err != nil {
  470. return playSeconds, err
  471. }
  472. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  473. }
  474. return
  475. }
  476. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  477. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  478. tradeCode = strings.Trim(tradeCode, " ")
  479. tradeCodeInt, err := strconv.Atoi(tradeCode)
  480. if err != nil {
  481. return
  482. }
  483. tradeCodeInt = tradeCodeInt + 1
  484. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  485. return
  486. }
  487. // excel日期字段格式化 yyyy-mm-dd
  488. func ConvertToFormatDay(excelDaysString string) string {
  489. // 2006-01-02 距离 1900-01-01的天数
  490. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  491. curDiffDay := excelDaysString
  492. b, _ := strconv.Atoi(curDiffDay)
  493. // 获取excel的日期距离2006-01-02的天数
  494. realDiffDay := b - baseDiffDay
  495. //fmt.Println("realDiffDay:",realDiffDay)
  496. // 距离2006-01-02 秒数
  497. realDiffSecond := realDiffDay * 24 * 3600
  498. //fmt.Println("realDiffSecond:",realDiffSecond)
  499. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  500. baseOriginSecond := 1136185445
  501. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  502. return resultTime
  503. }
  504. func GetLocalIP() (ip string, err error) {
  505. addrs, err := net.InterfaceAddrs()
  506. if err != nil {
  507. return
  508. }
  509. for _, addr := range addrs {
  510. ipAddr, ok := addr.(*net.IPNet)
  511. if !ok {
  512. continue
  513. }
  514. if ipAddr.IP.IsLoopback() {
  515. continue
  516. }
  517. if !ipAddr.IP.IsGlobalUnicast() {
  518. continue
  519. }
  520. return ipAddr.IP.String(), nil
  521. }
  522. return
  523. }
  524. func TimeTransferString(format string, t time.Time) string {
  525. str := t.Format(format)
  526. if t.IsZero() {
  527. return ""
  528. }
  529. return str
  530. }