common.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. package utils
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "gorm.io/gorm"
  13. "image"
  14. "image/png"
  15. "math"
  16. "math/rand"
  17. "net"
  18. "os"
  19. "regexp"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. )
  25. func GetRandString(size int) string {
  26. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  27. randomSb := ""
  28. digitSize := len(allLetterDigit)
  29. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  30. for i := 0; i < size; i++ {
  31. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  32. }
  33. return randomSb
  34. }
  35. func GetRandStringNoSpecialChar(size int) string {
  36. 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"}
  37. randomSb := ""
  38. digitSize := len(allLetterDigit)
  39. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  40. for i := 0; i < size; i++ {
  41. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  42. }
  43. return randomSb
  44. }
  45. func StringsToJSON(str string) string {
  46. rs := []rune(str)
  47. jsons := ""
  48. for _, r := range rs {
  49. rint := int(r)
  50. if rint < 128 {
  51. jsons += string(r)
  52. } else {
  53. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  54. }
  55. }
  56. return jsons
  57. }
  58. // 序列化
  59. func ToString(v interface{}) string {
  60. data, _ := json.Marshal(v)
  61. return string(data)
  62. }
  63. // md5加密
  64. func MD5(data string) string {
  65. m := md5.Sum([]byte(data))
  66. return hex.EncodeToString(m[:])
  67. }
  68. func GetToday(format string) string {
  69. today := time.Now().Format(format)
  70. return today
  71. }
  72. // 获取今天剩余秒数
  73. func GetTodayLastSecond() time.Duration {
  74. today := GetToday(FormatDate) + " 23:59:59"
  75. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  76. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  77. }
  78. // 处理出生日期函数
  79. func GetBrithDate(idcard string) string {
  80. l := len(idcard)
  81. var s string
  82. if l == 15 {
  83. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  84. return s
  85. }
  86. if l == 18 {
  87. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  88. return s
  89. }
  90. return GetToday(FormatDate)
  91. }
  92. // 处理性别
  93. func WhichSexByIdcard(idcard string) string {
  94. var sexs = [2]string{"女", "男"}
  95. length := len(idcard)
  96. if length == 18 {
  97. sex, _ := strconv.Atoi(string(idcard[16]))
  98. return sexs[sex%2]
  99. } else if length == 15 {
  100. sex, _ := strconv.Atoi(string(idcard[14]))
  101. return sexs[sex%2]
  102. }
  103. return "男"
  104. }
  105. // 截取小数点后几位
  106. func SubFloatToString(f float64, m int) string {
  107. n := strconv.FormatFloat(f, 'f', -1, 64)
  108. if n == "" {
  109. return ""
  110. }
  111. if m >= len(n) {
  112. return n
  113. }
  114. newn := strings.Split(n, ".")
  115. if m == 0 {
  116. return newn[0]
  117. }
  118. if len(newn) < 2 || m >= len(newn[1]) {
  119. return n
  120. }
  121. return newn[0] + "." + newn[1][:m]
  122. }
  123. // 截取小数点后几位
  124. func SubFloatToFloat(f float64, m int) float64 {
  125. newn := SubFloatToString(f, m)
  126. newf, _ := strconv.ParseFloat(newn, 64)
  127. return newf
  128. }
  129. // 获取相差时间-年
  130. func GetYearDiffer(start_time, end_time string) int {
  131. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  132. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  133. age := t2.Year() - t1.Year()
  134. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  135. age--
  136. }
  137. return age
  138. }
  139. // 获取相差时间-秒
  140. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  141. diff := end_time.Unix() - start_time.Unix()
  142. return diff
  143. }
  144. func FixFloat(f float64, m int) float64 {
  145. newn := SubFloatToString(f+0.00000001, m)
  146. newf, _ := strconv.ParseFloat(newn, 64)
  147. return newf
  148. }
  149. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  150. func StrListToString(strList []string) (str string) {
  151. if len(strList) > 0 {
  152. for k, v := range strList {
  153. if k == 0 {
  154. str = v
  155. } else {
  156. str = str + "," + v
  157. }
  158. }
  159. return
  160. }
  161. return ""
  162. }
  163. // Token
  164. //func GetToken() string {
  165. // randStr := GetRandString(64)
  166. // token := MD5(randStr + Md5Key)
  167. // tokenLen := 64 - len(token)
  168. // return strings.ToUpper(token + GetRandString(tokenLen))
  169. //}
  170. // 数据没有记录
  171. func ErrNoRow() string {
  172. return "<QuerySeter> no row found"
  173. }
  174. // IsErrNoRow
  175. // @Description: 判断是否是gorm的查询不到数据的报错
  176. // @param err
  177. // @return bool
  178. func IsErrNoRow(err error) bool {
  179. if err == nil {
  180. return false
  181. }
  182. return errors.Is(err, gorm.ErrRecordNotFound)
  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 GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  446. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  447. tradeCode = strings.Trim(tradeCode, " ")
  448. tradeCodeInt, err := strconv.Atoi(tradeCode)
  449. if err != nil {
  450. return
  451. }
  452. tradeCodeInt = tradeCodeInt + 1
  453. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  454. return
  455. }
  456. // excel日期字段格式化 yyyy-mm-dd
  457. func ConvertToFormatDay(excelDaysString string) string {
  458. // 2006-01-02 距离 1900-01-01的天数
  459. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  460. curDiffDay := excelDaysString
  461. b, _ := strconv.Atoi(curDiffDay)
  462. // 获取excel的日期距离2006-01-02的天数
  463. realDiffDay := b - baseDiffDay
  464. //fmt.Println("realDiffDay:",realDiffDay)
  465. // 距离2006-01-02 秒数
  466. realDiffSecond := realDiffDay * 24 * 3600
  467. //fmt.Println("realDiffSecond:",realDiffSecond)
  468. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  469. baseOriginSecond := 1136185445
  470. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  471. return resultTime
  472. }
  473. func GetLocalIP() (ip string, err error) {
  474. addrs, err := net.InterfaceAddrs()
  475. if err != nil {
  476. return
  477. }
  478. for _, addr := range addrs {
  479. ipAddr, ok := addr.(*net.IPNet)
  480. if !ok {
  481. continue
  482. }
  483. if ipAddr.IP.IsLoopback() {
  484. continue
  485. }
  486. if !ipAddr.IP.IsGlobalUnicast() {
  487. continue
  488. }
  489. return ipAddr.IP.String(), nil
  490. }
  491. return
  492. }
  493. func TimeTransferString(format string, t time.Time) string {
  494. str := t.Format(format)
  495. if t.IsZero() {
  496. return ""
  497. }
  498. return str
  499. }
  500. // HmacSha256 计算HmacSha256
  501. // key 是加密所使用的key
  502. // data 是加密的内容
  503. func HmacSha256(key string, data string) []byte {
  504. mac := hmac.New(sha256.New, []byte(key))
  505. _, _ = mac.Write([]byte(data))
  506. return mac.Sum(nil)
  507. }
  508. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  509. func HmacSha256ToBase64(key string, data string) string {
  510. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  511. }
  512. func GetSign(nonce, timestamp string) (sign string) {
  513. signStrMap := map[string]string{
  514. "nonce": nonce,
  515. "timestamp": timestamp,
  516. "appid": AppId,
  517. }
  518. keys := make([]string, 0, len(signStrMap))
  519. for k := range signStrMap {
  520. keys = append(keys, k)
  521. }
  522. sort.Strings(keys)
  523. var signStr string
  524. for _, k := range keys {
  525. signStr += k + "=" + signStrMap[k] + "&"
  526. }
  527. signStr = strings.Trim(signStr, "&")
  528. fmt.Println("signStr:" + signStr)
  529. sign = HmacSha256ToBase64(Secret, signStr)
  530. fmt.Println("sign:" + sign)
  531. return
  532. }
  533. // GetOrmInReplace 获取orm的in查询替换?的方法
  534. func GetOrmInReplace(num int) string {
  535. //template := make([]string, num)
  536. //for i := 0; i < num; i++ {
  537. // template[i] = "?"
  538. //}
  539. //return strings.Join(template, ",")
  540. return "?"
  541. }
  542. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  543. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  544. for _, id := range idIntList {
  545. if id == searchId {
  546. has = true
  547. return
  548. }
  549. }
  550. return
  551. }
  552. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  553. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  554. for _, id := range idStrList {
  555. if id == searchId {
  556. has = true
  557. return
  558. }
  559. }
  560. return
  561. }