common.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "encoding/json"
  13. "fmt"
  14. "image"
  15. "image/png"
  16. "io"
  17. "math"
  18. "math/rand"
  19. "net"
  20. "net/http"
  21. "os"
  22. "os/exec"
  23. "path"
  24. "regexp"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "github.com/shopspring/decimal"
  30. )
  31. // 随机数种子
  32. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  33. func GetRandString(size int) string {
  34. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  35. randomSb := ""
  36. digitSize := len(allLetterDigit)
  37. for i := 0; i < size; i++ {
  38. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  39. }
  40. return randomSb
  41. }
  42. func GetRandStringNoSpecialChar(size int) string {
  43. 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"}
  44. randomSb := ""
  45. digitSize := len(allLetterDigit)
  46. for i := 0; i < size; i++ {
  47. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  48. }
  49. return randomSb
  50. }
  51. func StringsToJSON(str string) string {
  52. rs := []rune(str)
  53. jsons := ""
  54. for _, r := range rs {
  55. rint := int(r)
  56. if rint < 128 {
  57. jsons += string(r)
  58. } else {
  59. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  60. }
  61. }
  62. return jsons
  63. }
  64. // 序列化
  65. func ToString(v interface{}) string {
  66. data, _ := json.Marshal(v)
  67. return string(data)
  68. }
  69. // md5加密
  70. func MD5(data string) string {
  71. m := md5.Sum([]byte(data))
  72. return hex.EncodeToString(m[:])
  73. }
  74. // 获取数字随机字符
  75. func GetRandDigit(n int) string {
  76. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  77. }
  78. // 获取随机数
  79. func GetRandNumber(n int) int {
  80. return rnd.Intn(n)
  81. }
  82. func GetRandInt(min, max int) int {
  83. if min >= max || min == 0 || max == 0 {
  84. return max
  85. }
  86. return rand.Intn(max-min) + min
  87. }
  88. func GetToday(format string) string {
  89. today := time.Now().Format(format)
  90. return today
  91. }
  92. // 获取今天剩余秒数
  93. func GetTodayLastSecond() time.Duration {
  94. today := GetToday(FormatDate) + " 23:59:59"
  95. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  96. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  97. }
  98. // 处理出生日期函数
  99. func GetBrithDate(idcard string) string {
  100. l := len(idcard)
  101. var s string
  102. if l == 15 {
  103. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  104. return s
  105. }
  106. if l == 18 {
  107. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  108. return s
  109. }
  110. return GetToday(FormatDate)
  111. }
  112. // 处理性别
  113. func WhichSexByIdcard(idcard string) string {
  114. var sexs = [2]string{"女", "男"}
  115. length := len(idcard)
  116. if length == 18 {
  117. sex, _ := strconv.Atoi(string(idcard[16]))
  118. return sexs[sex%2]
  119. } else if length == 15 {
  120. sex, _ := strconv.Atoi(string(idcard[14]))
  121. return sexs[sex%2]
  122. }
  123. return "男"
  124. }
  125. // 截取小数点后几位
  126. func SubFloatToString(f float64, m int) string {
  127. n := strconv.FormatFloat(f, 'f', -1, 64)
  128. if n == "" {
  129. return ""
  130. }
  131. if m >= len(n) {
  132. return n
  133. }
  134. newn := strings.Split(n, ".")
  135. if m == 0 {
  136. return newn[0]
  137. }
  138. if len(newn) < 2 || m >= len(newn[1]) {
  139. return n
  140. }
  141. return newn[0] + "." + newn[1][:m]
  142. }
  143. // 截取小数点后几位
  144. func SubFloatToFloat(f float64, m int) float64 {
  145. newn := SubFloatToString(f, m)
  146. newf, _ := strconv.ParseFloat(newn, 64)
  147. return newf
  148. }
  149. // 截取小数点后几位
  150. func SubFloatToFloatStr(f float64, m int) string {
  151. newn := SubFloatToString(f, m)
  152. return newn
  153. }
  154. // 获取相差时间-年
  155. func GetYearDiffer(start_time, end_time string) int {
  156. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  157. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  158. age := t2.Year() - t1.Year()
  159. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  160. age--
  161. }
  162. return age
  163. }
  164. // 获取相差时间-秒
  165. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  166. diff := end_time.Unix() - start_time.Unix()
  167. return diff
  168. }
  169. func FixFloat(f float64, m int) float64 {
  170. newn := SubFloatToString(f+0.00000001, m)
  171. newf, _ := strconv.ParseFloat(newn, 64)
  172. return newf
  173. }
  174. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  175. func StrListToString(strList []string) (str string) {
  176. if len(strList) > 0 {
  177. for k, v := range strList {
  178. if k == 0 {
  179. str = v
  180. } else {
  181. str = str + "," + v
  182. }
  183. }
  184. return
  185. }
  186. return ""
  187. }
  188. // 数据没有记录
  189. func ErrNoRow() string {
  190. return "<QuerySeter> no row found"
  191. }
  192. // 校验邮箱格式
  193. func ValidateEmailFormatat(email string) bool {
  194. reg := regexp.MustCompile(RegularEmail)
  195. return reg.MatchString(email)
  196. }
  197. // 验证是否是手机号
  198. func ValidateMobileFormatat(mobileNum string) bool {
  199. reg := regexp.MustCompile(RegularMobile)
  200. return reg.MatchString(mobileNum)
  201. }
  202. // 判断文件是否存在
  203. func FileIsExist(filePath string) bool {
  204. _, err := os.Stat(filePath)
  205. return err == nil || os.IsExist(err)
  206. }
  207. // 获取图片扩展名
  208. func GetImgExt(file string) (ext string, err error) {
  209. var headerByte []byte
  210. headerByte = make([]byte, 8)
  211. fd, err := os.Open(file)
  212. if err != nil {
  213. return "", err
  214. }
  215. defer fd.Close()
  216. _, err = fd.Read(headerByte)
  217. if err != nil {
  218. return "", err
  219. }
  220. xStr := fmt.Sprintf("%x", headerByte)
  221. switch {
  222. case xStr == "89504e470d0a1a0a":
  223. ext = ".png"
  224. case xStr == "0000010001002020":
  225. ext = ".ico"
  226. case xStr == "0000020001002020":
  227. ext = ".cur"
  228. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  229. ext = ".gif"
  230. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  231. ext = ".tga"
  232. case xStr[:8] == "464f524d":
  233. ext = ".iff"
  234. case xStr[:8] == "52494646":
  235. ext = ".ani"
  236. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  237. ext = ".tiff"
  238. case xStr[:4] == "424d":
  239. ext = ".bmp"
  240. case xStr[:4] == "ffd8":
  241. ext = ".jpg"
  242. case xStr[:2] == "0a":
  243. ext = ".pcx"
  244. default:
  245. ext = ""
  246. }
  247. return ext, nil
  248. }
  249. // 保存图片
  250. func SaveImage(path string, img image.Image) (err error) {
  251. //需要保持的文件
  252. imgfile, err := os.Create(path)
  253. defer imgfile.Close()
  254. // 以PNG格式保存文件
  255. err = png.Encode(imgfile, img)
  256. return err
  257. }
  258. // 下载图片
  259. func DownloadImage(imgUrl string) (filePath string, err error) {
  260. imgPath := "./static/imgs/"
  261. fileName := path.Base(imgUrl)
  262. res, err := http.Get(imgUrl)
  263. if err != nil {
  264. fmt.Println("A error occurred!")
  265. return
  266. }
  267. defer res.Body.Close()
  268. // 获得get请求响应的reader对象
  269. reader := bufio.NewReaderSize(res.Body, 32*1024)
  270. filePath = imgPath + fileName
  271. file, err := os.Create(filePath)
  272. if err != nil {
  273. return
  274. }
  275. // 获得文件的writer对象
  276. writer := bufio.NewWriter(file)
  277. written, _ := io.Copy(writer, reader)
  278. fmt.Printf("Total length: %d \n", written)
  279. return
  280. }
  281. // 保存base64数据为文件
  282. func SaveBase64ToFile(content, path string) error {
  283. data, err := base64.StdEncoding.DecodeString(content)
  284. if err != nil {
  285. return err
  286. }
  287. f, err := os.Create(path)
  288. defer f.Close()
  289. if err != nil {
  290. return err
  291. }
  292. f.Write(data)
  293. return nil
  294. }
  295. func SaveBase64ToFileBySeek(content, path string) (err error) {
  296. data, err := base64.StdEncoding.DecodeString(content)
  297. exist, err := PathExists(path)
  298. if err != nil {
  299. return
  300. }
  301. if !exist {
  302. f, err := os.Create(path)
  303. if err != nil {
  304. return err
  305. }
  306. n, _ := f.Seek(0, 2)
  307. // 从末尾的偏移量开始写入内容
  308. _, err = f.WriteAt([]byte(data), n)
  309. defer f.Close()
  310. } else {
  311. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  312. if err != nil {
  313. return err
  314. }
  315. n, _ := f.Seek(0, 2)
  316. // 从末尾的偏移量开始写入内容
  317. _, err = f.WriteAt([]byte(data), n)
  318. defer f.Close()
  319. }
  320. return nil
  321. }
  322. func PathExists(path string) (bool, error) {
  323. _, err := os.Stat(path)
  324. if err == nil {
  325. return true, nil
  326. }
  327. if os.IsNotExist(err) {
  328. return false, nil
  329. }
  330. return false, err
  331. }
  332. func StartIndex(page, pagesize int) int {
  333. if page > 1 {
  334. return (page - 1) * pagesize
  335. }
  336. return 0
  337. }
  338. func PageCount(count, pagesize int) int {
  339. if count%pagesize > 0 {
  340. return count/pagesize + 1
  341. } else {
  342. return count / pagesize
  343. }
  344. }
  345. func TrimHtml(src string) string {
  346. //将HTML标签全转换成小写
  347. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  348. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  349. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  350. src = re.ReplaceAllString(src, "[图片]")
  351. re, _ = regexp.Compile("class[\\S\\s]+?>")
  352. src = re.ReplaceAllString(src, "")
  353. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  354. src = re.ReplaceAllString(src, "")
  355. return strings.TrimSpace(src)
  356. }
  357. //1556164246 -> 2019-04-25 03:50:46 +0000
  358. //timestamp
  359. func TimeToTimestamp() {
  360. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  361. }
  362. func ToUnicode(text string) string {
  363. textQuoted := strconv.QuoteToASCII(text)
  364. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  365. return textUnquoted
  366. }
  367. func VersionToInt(version string) int {
  368. version = strings.Replace(version, ".", "", -1)
  369. n, _ := strconv.Atoi(version)
  370. return n
  371. }
  372. func IsCheckInList(list []int, s int) bool {
  373. for _, v := range list {
  374. if v == s {
  375. return true
  376. }
  377. }
  378. return false
  379. }
  380. func round(num float64) int {
  381. return int(num + math.Copysign(0.5, num))
  382. }
  383. func toFixed(num float64, precision int) float64 {
  384. output := math.Pow(10, float64(precision))
  385. return float64(round(num*output)) / output
  386. }
  387. // GetWilsonScore returns Wilson Score
  388. func GetWilsonScore(p, n float64) float64 {
  389. if p == 0 && n == 0 {
  390. return 0
  391. }
  392. 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)
  393. }
  394. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  395. func ChangeWordsToNum(str string) (numStr string) {
  396. words := ([]rune)(str)
  397. num := 0
  398. n := 0
  399. for i := 0; i < len(words); i++ {
  400. word := string(words[i : i+1])
  401. switch word {
  402. case "万":
  403. if n == 0 {
  404. n = 1
  405. }
  406. n = n * 10000
  407. num = num*10000 + n
  408. n = 0
  409. case "千":
  410. if n == 0 {
  411. n = 1
  412. }
  413. n = n * 1000
  414. num += n
  415. n = 0
  416. case "百":
  417. if n == 0 {
  418. n = 1
  419. }
  420. n = n * 100
  421. num += n
  422. n = 0
  423. case "十":
  424. if n == 0 {
  425. n = 1
  426. }
  427. n = n * 10
  428. num += n
  429. n = 0
  430. case "一":
  431. n += 1
  432. case "二":
  433. n += 2
  434. case "三":
  435. n += 3
  436. case "四":
  437. n += 4
  438. case "五":
  439. n += 5
  440. case "六":
  441. n += 6
  442. case "七":
  443. n += 7
  444. case "八":
  445. n += 8
  446. case "九":
  447. n += 9
  448. case "零":
  449. default:
  450. if n > 0 {
  451. num += n
  452. n = 0
  453. }
  454. if num == 0 {
  455. numStr += word
  456. } else {
  457. numStr += strconv.Itoa(num) + word
  458. num = 0
  459. }
  460. }
  461. }
  462. if n > 0 {
  463. num += n
  464. n = 0
  465. }
  466. if num != 0 {
  467. numStr += strconv.Itoa(num)
  468. }
  469. return
  470. }
  471. func Sha1(data string) string {
  472. sha1 := sha1.New()
  473. sha1.Write([]byte(data))
  474. return hex.EncodeToString(sha1.Sum([]byte("")))
  475. }
  476. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  477. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  478. out, err := exec.Command("bash", "-c", cmd).Output()
  479. if err != nil {
  480. return
  481. }
  482. outTimes := string(out)
  483. fmt.Println("outTimes:", outTimes)
  484. if outTimes != "" {
  485. timeArr := strings.Split(outTimes, ":")
  486. h := timeArr[0]
  487. m := timeArr[1]
  488. s := timeArr[2]
  489. hInt, err := strconv.Atoi(h)
  490. if err != nil {
  491. return playSeconds, err
  492. }
  493. mInt, err := strconv.Atoi(m)
  494. if err != nil {
  495. return playSeconds, err
  496. }
  497. s = strings.Trim(s, " ")
  498. s = strings.Trim(s, "\n")
  499. sInt, err := strconv.ParseFloat(s, 64)
  500. if err != nil {
  501. return playSeconds, err
  502. }
  503. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  504. }
  505. return
  506. }
  507. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  508. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  509. tradeCode = strings.Trim(tradeCode, " ")
  510. tradeCodeInt, err := strconv.Atoi(tradeCode)
  511. if err != nil {
  512. return
  513. }
  514. tradeCodeInt = tradeCodeInt + 1
  515. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  516. return
  517. }
  518. // excel日期字段格式化 yyyy-mm-dd
  519. func ConvertToFormatDay(excelDaysString string) string {
  520. // 2006-01-02 距离 1900-01-01的天数
  521. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  522. curDiffDay := excelDaysString
  523. b, _ := strconv.Atoi(curDiffDay)
  524. // 获取excel的日期距离2006-01-02的天数
  525. realDiffDay := b - baseDiffDay
  526. //fmt.Println("realDiffDay:",realDiffDay)
  527. // 距离2006-01-02 秒数
  528. realDiffSecond := realDiffDay * 24 * 3600
  529. //fmt.Println("realDiffSecond:",realDiffSecond)
  530. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  531. baseOriginSecond := 1136185445
  532. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  533. return resultTime
  534. }
  535. func CheckPwd(pwd string) bool {
  536. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  537. reg := regexp.MustCompile(compile)
  538. flag := reg.MatchString(pwd)
  539. return flag
  540. }
  541. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  542. // 数字月份必须前置补零
  543. if len(myMonth) == 1 {
  544. myMonth = "0" + myMonth
  545. }
  546. yInt, _ := strconv.Atoi(myYear)
  547. timeLayout := "2006-01-02 15:04:05"
  548. loc, _ := time.LoadLocation("Local")
  549. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  550. newMonth := theTime.Month()
  551. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  552. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  553. return t1, t2
  554. }
  555. // 移除字符串中的空格
  556. func TrimStr(str string) (str2 string) {
  557. return strings.Replace(str, " ", "", -1)
  558. }
  559. // 字符串转换为time
  560. func StrTimeToTime(strTime string) time.Time {
  561. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  562. loc, _ := time.LoadLocation("Local") //重要:获取时区
  563. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  564. return resultTime
  565. }
  566. // GetOrmInReplace 获取orm的in查询替换?的方法
  567. func GetOrmInReplace(num int) string {
  568. template := make([]string, num)
  569. for i := 0; i < num; i++ {
  570. template[i] = "?"
  571. }
  572. return strings.Join(template, ",")
  573. }
  574. // RevSlice 反转切片
  575. func RevSlice(slice []int) []int {
  576. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  577. slice[i], slice[j] = slice[j], slice[i]
  578. }
  579. return slice
  580. }
  581. // GetTimeSubDay 计算两个时间的自然日期差
  582. func GetTimeSubDay(t1, t2 time.Time) int {
  583. var day int
  584. swap := false
  585. if t1.Unix() > t2.Unix() {
  586. t1, t2 = t2, t1
  587. swap = true
  588. }
  589. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  590. day = int(t2.Sub(t1).Hours() / 24)
  591. // 计算在t1+两个时间的余数之后天数是否有变化
  592. if t1_.Day() != t1.Day() {
  593. day += 1
  594. }
  595. if swap {
  596. day = -day
  597. }
  598. return day
  599. }
  600. // GetDaysBetween2Date 计算两个日期之间相差几天
  601. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  602. // 将字符串转化为Time格式
  603. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  604. if err != nil {
  605. return 0, err
  606. }
  607. // 将字符串转化为Time格式
  608. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  609. if err != nil {
  610. return 0, err
  611. }
  612. //计算相差天数
  613. return int(date1.Sub(date2).Hours() / 24), nil
  614. }
  615. // MapSorter 对于map 排序
  616. type MapSorter []Item
  617. type Item struct {
  618. Key int
  619. Val float64
  620. }
  621. func NewMapSorter(m map[int]float64) MapSorter {
  622. ms := make(MapSorter, 0, len(m))
  623. for k, v := range m {
  624. ms = append(ms, Item{k, v})
  625. }
  626. return ms
  627. }
  628. func (ms MapSorter) Len() int {
  629. return len(ms)
  630. }
  631. func (ms MapSorter) Less(i, j int) bool {
  632. return ms[i].Val > ms[j].Val // 按值排序
  633. //return ms[i].Key < ms[j].Key // 按键排序
  634. }
  635. func (ms MapSorter) Swap(i, j int) {
  636. ms[i], ms[j] = ms[j], ms[i]
  637. }
  638. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  639. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  640. for _, id := range idIntList {
  641. if id == searchId {
  642. has = true
  643. return
  644. }
  645. }
  646. return
  647. }
  648. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  649. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  650. for _, id := range idStrList {
  651. if id == searchId {
  652. has = true
  653. return
  654. }
  655. }
  656. return
  657. }
  658. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  659. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  660. startDate = tmpStartDate
  661. endDate = tmpEndDate
  662. switch dateType {
  663. case 1:
  664. startDate = "2000-01-01"
  665. endDate = ""
  666. case 2:
  667. startDate = "2010-01-01"
  668. endDate = ""
  669. case 3:
  670. startDate = "2015-01-01"
  671. endDate = ""
  672. case 4:
  673. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  674. startDate = "2021-01-01"
  675. endDate = ""
  676. case 5:
  677. //startDate = startDate + "-01"
  678. //endDate = endDate + "-01"
  679. case 6:
  680. //startDate = startDate + "-01"
  681. endDate = ""
  682. case 7:
  683. startDate = "2018-01-01"
  684. endDate = ""
  685. case 8:
  686. startDate = "2019-01-01"
  687. endDate = ""
  688. case 9:
  689. startDate = "2020-01-01"
  690. endDate = ""
  691. case 11:
  692. startDate = "2022-01-01"
  693. endDate = ""
  694. }
  695. // 兼容日期错误
  696. {
  697. if strings.Count(startDate, "-") == 1 {
  698. startDate = startDate + "-01"
  699. }
  700. if strings.Count(endDate, "-") == 1 {
  701. endDate = endDate + "-01"
  702. }
  703. }
  704. return
  705. }
  706. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  707. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  708. switch dateType {
  709. case 1:
  710. startDate = currDate.AddDate(0, -3, 0)
  711. case 2:
  712. startDate = currDate.AddDate(0, -6, 0)
  713. case 3:
  714. startDate = currDate.AddDate(-1, 0, 0)
  715. case 4:
  716. startDate = currDate.AddDate(-2, 0, 0)
  717. case 5:
  718. startDate = currDate.AddDate(-3, 0, 0)
  719. case 6:
  720. startDate = currDate.AddDate(-5, 0, 0)
  721. case 7:
  722. startDate = currDate.AddDate(-10, 0, 0)
  723. }
  724. return
  725. }
  726. // GetCeilNewNum 保留n位有效数字的向上取整
  727. // @params num 实际数据
  728. // @params baseLen 需要保留的有效位数
  729. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  730. if num >= 1 {
  731. tmpNum := int(math.Ceil(num)) // 向上取整
  732. str := strconv.Itoa(tmpNum)
  733. lenStr := len(str)
  734. if lenStr > baseLen {
  735. newNumStr := str[0:baseLen]
  736. newNumInt, _ := strconv.Atoi(newNumStr)
  737. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  738. if newNum < num {
  739. newNumInt += 1
  740. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  741. }
  742. } else {
  743. newNum = float64(tmpNum)
  744. }
  745. return
  746. } else if num > 0 {
  747. // 这是小数
  748. str := strconv.FormatFloat(num, 'f', -1, 64)
  749. // 去除小数点和负号
  750. str = removeDecimalPoint(str)
  751. // 计算字符串长度
  752. lenStr := len(str)
  753. if lenStr > baseLen {
  754. newNumStr := str[0:baseLen]
  755. newNumInt, _ := strconv.Atoi(newNumStr)
  756. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  757. if newNum < num {
  758. newNumInt += 1
  759. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  760. }
  761. } else {
  762. newNum = num
  763. }
  764. } else if num > -1 {
  765. // 这是小数
  766. str := strconv.FormatFloat(num, 'f', -1, 64)
  767. // 去除小数点和负号
  768. str = removeDecimalPoint(str)
  769. // 计算字符串长度
  770. lenStr := len(str)
  771. if lenStr > baseLen {
  772. newNumStr := str[0:baseLen]
  773. newNumInt, _ := strconv.Atoi(newNumStr)
  774. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  775. newNum = -newNum
  776. if newNum < num {
  777. newNumInt -= 1
  778. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  779. newNum = -newNum
  780. }
  781. } else {
  782. newNum = num
  783. }
  784. if newNum == -0 {
  785. newNum = 0
  786. }
  787. } else { // 小于等于-1
  788. tmpNumFloat := math.Abs(num)
  789. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  790. str := strconv.Itoa(tmpNum)
  791. lenStr := len(str)
  792. if lenStr > baseLen {
  793. newNumStr := str[0:baseLen]
  794. //fmt.Println("newNumStr:", newNumStr)
  795. newNumInt, _ := strconv.Atoi(newNumStr)
  796. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  797. newNum = -newNum
  798. if newNum < num {
  799. newNumInt -= 1
  800. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  801. newNum = -newNum
  802. }
  803. } else {
  804. newNum = float64(-tmpNum)
  805. }
  806. }
  807. return
  808. }
  809. // GetFloorNewNum 保留n位有效数字的向下取整
  810. // @params num 实际数据
  811. // @params baseLen 需要保留的有效位数
  812. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  813. if num >= 1 {
  814. tmpNum := int(math.Floor(num)) // 向上取整
  815. str := strconv.Itoa(tmpNum)
  816. lenStr := len(str)
  817. if lenStr > baseLen {
  818. newNumStr := str[0:baseLen]
  819. newNumInt, _ := strconv.Atoi(newNumStr)
  820. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  821. if newNum < num {
  822. newNumInt -= 1
  823. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  824. }
  825. } else {
  826. newNum = float64(tmpNum)
  827. }
  828. return
  829. } else if num > 0 {
  830. // 这是小数
  831. str := strconv.FormatFloat(num, 'f', -1, 64)
  832. // 去除小数点和负号
  833. str = removeDecimalPoint(str)
  834. // 计算字符串长度
  835. lenStr := len(str)
  836. if lenStr > baseLen {
  837. newNumStr := str[0:baseLen]
  838. newNumInt, _ := strconv.Atoi(newNumStr)
  839. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  840. if newNum > num {
  841. newNumInt -= 1
  842. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  843. }
  844. } else {
  845. newNum = num
  846. }
  847. } else if num > -1 {
  848. // 这是小数
  849. str := strconv.FormatFloat(num, 'f', -1, 64)
  850. // 去除小数点和负号
  851. str = removeDecimalPoint(str)
  852. // 计算字符串长度
  853. lenStr := len(str)
  854. if lenStr > baseLen {
  855. newNumStr := str[0:baseLen]
  856. newNumInt, _ := strconv.Atoi(newNumStr)
  857. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  858. newNum = -newNum
  859. if newNum > num {
  860. newNumInt += 1
  861. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  862. newNum = -newNum
  863. }
  864. } else {
  865. newNum = num
  866. }
  867. if newNum == -0 {
  868. newNum = 0
  869. }
  870. } else { // 小于等于-1
  871. tmpNumFloat := math.Abs(num)
  872. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  873. str := strconv.Itoa(tmpNum)
  874. lenStr := len(str)
  875. if lenStr > baseLen {
  876. newNumStr := str[0:baseLen]
  877. //fmt.Println("newNumStr:", newNumStr)
  878. newNumInt, _ := strconv.Atoi(newNumStr)
  879. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  880. newNum = -newNum
  881. if newNum > num {
  882. newNumInt += 1
  883. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  884. newNum = -newNum
  885. }
  886. } else {
  887. newNum = float64(-tmpNum)
  888. }
  889. }
  890. return
  891. }
  892. // 去除小数点和负号
  893. func removeDecimalPoint(str string) string {
  894. // 去除小数点
  895. str = str[strings.Index(str, ".")+1:]
  896. return str
  897. }
  898. func GetLocalIP() (ip string, err error) {
  899. addrs, err := net.InterfaceAddrs()
  900. if err != nil {
  901. return
  902. }
  903. for _, addr := range addrs {
  904. ipAddr, ok := addr.(*net.IPNet)
  905. if !ok {
  906. continue
  907. }
  908. if ipAddr.IP.IsLoopback() {
  909. continue
  910. }
  911. if !ipAddr.IP.IsGlobalUnicast() {
  912. continue
  913. }
  914. return ipAddr.IP.String(), nil
  915. }
  916. return
  917. }
  918. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  919. startDate = tmpStartDate
  920. endDate = tmpEndDate
  921. switch dateType {
  922. case 1:
  923. startDate = "2000-01-01"
  924. endDate = ""
  925. case 2:
  926. startDate = "2010-01-01"
  927. endDate = ""
  928. case 3:
  929. startDate = "2015-01-01"
  930. endDate = ""
  931. case 4:
  932. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  933. startDate = "2021-01-01"
  934. endDate = ""
  935. case 5:
  936. //startDate = startDate + "-01"
  937. //endDate = endDate + "-01"
  938. case 6:
  939. //startDate = startDate + "-01"
  940. endDate = ""
  941. case 7:
  942. startDate = "2018-01-01"
  943. endDate = ""
  944. case 8:
  945. startDate = "2019-01-01"
  946. endDate = ""
  947. case 9:
  948. startDate = "2020-01-01"
  949. endDate = ""
  950. case 11:
  951. startDate = "2022-01-01"
  952. endDate = ""
  953. case DateTypeNYears:
  954. if startYear == 0 { //默认取最近5年
  955. startYear = 5
  956. }
  957. if yearMax == 0 {
  958. return
  959. }
  960. startYear = startYear - 1
  961. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  962. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  963. endDate = ""
  964. }
  965. // 兼容日期错误
  966. {
  967. if strings.Count(startDate, "-") == 1 {
  968. startDate = startDate + "-01"
  969. }
  970. if strings.Count(endDate, "-") == 1 {
  971. endDate = endDate + "-01"
  972. }
  973. }
  974. return
  975. }
  976. func GetColorMap() map[int]string {
  977. colorMap := make(map[int]string)
  978. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  979. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  980. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  981. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  982. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  983. for k, v := range colors {
  984. colorMap[k] = v
  985. }
  986. return colorMap
  987. }
  988. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  989. func GetDaysDiff1900(date string) int {
  990. // 将字符串转换为时间类型
  991. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  992. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  993. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  994. if err != nil {
  995. return 0
  996. }
  997. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  998. if err != nil {
  999. return 0
  1000. }
  1001. // 计算两个日期之间的天数差值
  1002. duration := tEnd.Sub(tStart).Hours() / 24
  1003. days := int(duration)
  1004. return days
  1005. }
  1006. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1007. funMap := getFormulaMap()
  1008. for k, v := range funMap {
  1009. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1010. }
  1011. replaceCount := 0
  1012. for tag, val := range valTagMap {
  1013. dvStr := fmt.Sprintf("%v", val)
  1014. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1015. replaceCount++
  1016. }
  1017. for k, v := range funMap {
  1018. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1019. }
  1020. return formulaStr
  1021. }
  1022. // GetFrequencyEn 获取频度的英文版
  1023. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1024. switch frequency {
  1025. case "日度":
  1026. frequencyEn = "day"
  1027. return
  1028. case "周度":
  1029. frequencyEn = "week"
  1030. return
  1031. case "旬度":
  1032. frequencyEn = "ten days"
  1033. return
  1034. case "月度":
  1035. frequencyEn = "month"
  1036. return
  1037. case "季度":
  1038. frequencyEn = "quarter"
  1039. return
  1040. case "年度":
  1041. frequencyEn = "year"
  1042. return
  1043. }
  1044. return
  1045. }
  1046. // DateConvMysqlConvMongo
  1047. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1048. // @author: Roc
  1049. // @datetime 2024-05-08 11:03:26
  1050. // @param dateCon string
  1051. func DateConvMysqlConvMongo(dateCon string) string {
  1052. cond := ""
  1053. switch dateCon {
  1054. case "=":
  1055. cond = "$eq"
  1056. case "<":
  1057. cond = "$lt"
  1058. case "<=":
  1059. cond = "$lte"
  1060. case ">":
  1061. cond = "$gt"
  1062. case ">=":
  1063. cond = "$gte"
  1064. }
  1065. return cond
  1066. }
  1067. // HmacSha256 计算HmacSha256
  1068. // key 是加密所使用的key
  1069. // data 是加密的内容
  1070. func HmacSha256(key string, data string) []byte {
  1071. mac := hmac.New(sha256.New, []byte(key))
  1072. _, _ = mac.Write([]byte(data))
  1073. return mac.Sum(nil)
  1074. }
  1075. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  1076. func HmacSha256ToBase64(key string, data string) string {
  1077. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  1078. }
  1079. func GetSign(nonce, timestamp, appId, secret string) (sign string) {
  1080. signStrMap := map[string]string{
  1081. "nonce": nonce,
  1082. "timestamp": timestamp,
  1083. "appid": appId,
  1084. }
  1085. keys := make([]string, 0, len(signStrMap))
  1086. for k := range signStrMap {
  1087. keys = append(keys, k)
  1088. }
  1089. sort.Strings(keys)
  1090. var signStr string
  1091. for _, k := range keys {
  1092. signStr += k + "=" + signStrMap[k] + "&"
  1093. }
  1094. signStr = strings.Trim(signStr, "&")
  1095. fmt.Println("signStr:" + signStr)
  1096. sign = HmacSha256ToBase64(secret, signStr)
  1097. return
  1098. }
  1099. func TimeTransferString(format string, t time.Time) string {
  1100. str := t.Format(format)
  1101. if t.IsZero() {
  1102. return ""
  1103. }
  1104. return str
  1105. }
  1106. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1107. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1108. remain := len(result) % 8
  1109. if remain > 0 {
  1110. mod := 8 - remain
  1111. for i := 0; i < mod; i++ {
  1112. result = append(result, 0)
  1113. }
  1114. }
  1115. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1116. if err != nil {
  1117. panic(any(err))
  1118. }
  1119. return origData
  1120. }
  1121. // // 3DES解密
  1122. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1123. block, err := des.NewTripleDESCipher(key)
  1124. if err != nil {
  1125. return nil, err
  1126. }
  1127. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1128. origData := make([]byte, len(crypted))
  1129. // origData := crypted
  1130. blockMode.CryptBlocks(origData, crypted)
  1131. origData = PKCS5UnPadding(origData)
  1132. // origData = ZeroUnPadding(origData)
  1133. return origData, nil
  1134. }
  1135. func PKCS5UnPadding(origData []byte) []byte {
  1136. length := len(origData)
  1137. // 去掉最后一个字节 unpadding 次
  1138. unpadding := int(origData[length-1])
  1139. return origData[:(length - unpadding)]
  1140. }