common.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. cryRand "crypto/rand"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "github.com/mozillazg/go-pinyin"
  13. "image"
  14. "image/png"
  15. "io"
  16. "io/ioutil"
  17. "math"
  18. "math/big"
  19. "math/rand"
  20. "net"
  21. "net/http"
  22. "net/http/cookiejar"
  23. "os"
  24. "os/exec"
  25. "path"
  26. "regexp"
  27. "strconv"
  28. "strings"
  29. "time"
  30. "unicode"
  31. )
  32. // 随机数种子
  33. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  34. func GetRandString(size int) string {
  35. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  36. randomSb := ""
  37. digitSize := len(allLetterDigit)
  38. for i := 0; i < size; i++ {
  39. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  40. }
  41. return randomSb
  42. }
  43. func GetRandStringNoSpecialChar(size int) string {
  44. 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"}
  45. randomSb := ""
  46. digitSize := len(allLetterDigit)
  47. for i := 0; i < size; i++ {
  48. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  49. }
  50. return randomSb
  51. }
  52. func StringsToJSON(str string) string {
  53. rs := []rune(str)
  54. jsons := ""
  55. for _, r := range rs {
  56. rint := int(r)
  57. if rint < 128 {
  58. jsons += string(r)
  59. } else {
  60. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  61. }
  62. }
  63. return jsons
  64. }
  65. // 序列化
  66. func ToString(v interface{}) string {
  67. data, _ := json.Marshal(v)
  68. return string(data)
  69. }
  70. // md5加密
  71. func MD5(data string) string {
  72. m := md5.Sum([]byte(data))
  73. return hex.EncodeToString(m[:])
  74. }
  75. // 获取数字随机字符
  76. func GetRandDigit(n int) string {
  77. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  78. }
  79. // 获取随机数
  80. func GetRandNumber(n int) int {
  81. return rnd.Intn(n)
  82. }
  83. func GetRandInt(min, max int) int {
  84. if min >= max || min == 0 || max == 0 {
  85. return max
  86. }
  87. return rand.Intn(max-min) + min
  88. }
  89. func GetToday(format string) string {
  90. today := time.Now().Format(format)
  91. return today
  92. }
  93. // 获取今天剩余秒数
  94. func GetTodayLastSecond() time.Duration {
  95. today := GetToday(FormatDate) + " 23:59:59"
  96. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  97. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  98. }
  99. // 处理出生日期函数
  100. func GetBrithDate(idcard string) string {
  101. l := len(idcard)
  102. var s string
  103. if l == 15 {
  104. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  105. return s
  106. }
  107. if l == 18 {
  108. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  109. return s
  110. }
  111. return GetToday(FormatDate)
  112. }
  113. // 处理性别
  114. func WhichSexByIdcard(idcard string) string {
  115. var sexs = [2]string{"女", "男"}
  116. length := len(idcard)
  117. if length == 18 {
  118. sex, _ := strconv.Atoi(string(idcard[16]))
  119. return sexs[sex%2]
  120. } else if length == 15 {
  121. sex, _ := strconv.Atoi(string(idcard[14]))
  122. return sexs[sex%2]
  123. }
  124. return "男"
  125. }
  126. // 截取小数点后几位
  127. func SubFloatToString(f float64, m int) string {
  128. n := strconv.FormatFloat(f, 'f', -1, 64)
  129. if n == "" {
  130. return ""
  131. }
  132. if m >= len(n) {
  133. return n
  134. }
  135. newn := strings.Split(n, ".")
  136. if m == 0 {
  137. return newn[0]
  138. }
  139. if len(newn) < 2 || m >= len(newn[1]) {
  140. return n
  141. }
  142. return newn[0] + "." + newn[1][:m]
  143. }
  144. // 截取小数点后几位
  145. func SubFloatToFloat(f float64, m int) float64 {
  146. newn := SubFloatToString(f, m)
  147. newf, _ := strconv.ParseFloat(newn, 64)
  148. return newf
  149. }
  150. // 截取小数点后几位
  151. func SubFloatToFloatStr(f float64, m int) string {
  152. newn := SubFloatToString(f, m)
  153. return newn
  154. }
  155. // 获取相差时间-年
  156. func GetYearDiffer(start_time, end_time string) int {
  157. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  158. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  159. age := t2.Year() - t1.Year()
  160. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  161. age--
  162. }
  163. return age
  164. }
  165. // 获取相差时间-秒
  166. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  167. diff := end_time.Unix() - start_time.Unix()
  168. return diff
  169. }
  170. func FixFloat(f float64, m int) float64 {
  171. newn := SubFloatToString(f+0.00000001, m)
  172. newf, _ := strconv.ParseFloat(newn, 64)
  173. return newf
  174. }
  175. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  176. func StrListToString(strList []string) (str string) {
  177. if len(strList) > 0 {
  178. for k, v := range strList {
  179. if k == 0 {
  180. str = v
  181. } else {
  182. str = str + "," + v
  183. }
  184. }
  185. return
  186. }
  187. return ""
  188. }
  189. // Token
  190. func GetToken() string {
  191. randStr := GetRandString(64)
  192. token := MD5(randStr + Md5Key)
  193. tokenLen := 64 - len(token)
  194. return strings.ToUpper(token + GetRandString(tokenLen))
  195. }
  196. // 数据没有记录
  197. func ErrNoRow() string {
  198. return "<QuerySeter> no row found"
  199. }
  200. // 判断文件是否存在
  201. func FileIsExist(filePath string) bool {
  202. _, err := os.Stat(filePath)
  203. return err == nil || os.IsExist(err)
  204. }
  205. // 获取图片扩展名
  206. func GetImgExt(file string) (ext string, err error) {
  207. var headerByte []byte
  208. headerByte = make([]byte, 8)
  209. fd, err := os.Open(file)
  210. if err != nil {
  211. return "", err
  212. }
  213. defer fd.Close()
  214. _, err = fd.Read(headerByte)
  215. if err != nil {
  216. return "", err
  217. }
  218. xStr := fmt.Sprintf("%x", headerByte)
  219. switch {
  220. case xStr == "89504e470d0a1a0a":
  221. ext = ".png"
  222. case xStr == "0000010001002020":
  223. ext = ".ico"
  224. case xStr == "0000020001002020":
  225. ext = ".cur"
  226. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  227. ext = ".gif"
  228. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  229. ext = ".tga"
  230. case xStr[:8] == "464f524d":
  231. ext = ".iff"
  232. case xStr[:8] == "52494646":
  233. ext = ".ani"
  234. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  235. ext = ".tiff"
  236. case xStr[:4] == "424d":
  237. ext = ".bmp"
  238. case xStr[:4] == "ffd8":
  239. ext = ".jpg"
  240. case xStr[:2] == "0a":
  241. ext = ".pcx"
  242. default:
  243. ext = ""
  244. }
  245. return ext, nil
  246. }
  247. // 保存图片
  248. func SaveImage(path string, img image.Image) (err error) {
  249. //需要保持的文件
  250. imgfile, err := os.Create(path)
  251. defer imgfile.Close()
  252. // 以PNG格式保存文件
  253. err = png.Encode(imgfile, img)
  254. return err
  255. }
  256. // 下载图片
  257. func DownloadImage(imgUrl string) (filePath string, err error) {
  258. imgPath := "./static/imgs/"
  259. fileName := path.Base(imgUrl)
  260. res, err := http.Get(imgUrl)
  261. if err != nil {
  262. fmt.Println("A error occurred!")
  263. return
  264. }
  265. defer res.Body.Close()
  266. // 获得get请求响应的reader对象
  267. reader := bufio.NewReaderSize(res.Body, 32*1024)
  268. filePath = imgPath + fileName
  269. file, err := os.Create(filePath)
  270. if err != nil {
  271. return
  272. }
  273. // 获得文件的writer对象
  274. writer := bufio.NewWriter(file)
  275. written, _ := io.Copy(writer, reader)
  276. fmt.Printf("Total length: %d \n", written)
  277. return
  278. }
  279. // 保存base64数据为文件
  280. func SaveBase64ToFile(content, path string) error {
  281. data, err := base64.StdEncoding.DecodeString(content)
  282. if err != nil {
  283. return err
  284. }
  285. f, err := os.Create(path)
  286. defer f.Close()
  287. if err != nil {
  288. return err
  289. }
  290. f.Write(data)
  291. return nil
  292. }
  293. func SaveBase64ToFileBySeek(content, path string) (err error) {
  294. data, err := base64.StdEncoding.DecodeString(content)
  295. exist, err := PathExists(path)
  296. if err != nil {
  297. return
  298. }
  299. if !exist {
  300. f, err := os.Create(path)
  301. if err != nil {
  302. return err
  303. }
  304. n, _ := f.Seek(0, 2)
  305. // 从末尾的偏移量开始写入内容
  306. _, err = f.WriteAt([]byte(data), n)
  307. defer f.Close()
  308. } else {
  309. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  310. if err != nil {
  311. return err
  312. }
  313. n, _ := f.Seek(0, 2)
  314. // 从末尾的偏移量开始写入内容
  315. _, err = f.WriteAt([]byte(data), n)
  316. defer f.Close()
  317. }
  318. return nil
  319. }
  320. func PathExists(path string) (bool, error) {
  321. _, err := os.Stat(path)
  322. if err == nil {
  323. return true, nil
  324. }
  325. if os.IsNotExist(err) {
  326. return false, nil
  327. }
  328. return false, err
  329. }
  330. func StartIndex(page, pagesize int) int {
  331. if page > 1 {
  332. return (page - 1) * pagesize
  333. }
  334. return 0
  335. }
  336. func PageCount(count, pagesize int) int {
  337. if count%pagesize > 0 {
  338. return count/pagesize + 1
  339. } else {
  340. return count / pagesize
  341. }
  342. }
  343. func TrimHtml(src string) string {
  344. //将HTML标签全转换成小写
  345. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  346. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  347. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  348. src = re.ReplaceAllString(src, "[图片]")
  349. re, _ = regexp.Compile("class[\\S\\s]+?>")
  350. src = re.ReplaceAllString(src, "")
  351. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  352. src = re.ReplaceAllString(src, "")
  353. return strings.TrimSpace(src)
  354. }
  355. //1556164246 -> 2019-04-25 03:50:46 +0000
  356. //timestamp
  357. func TimeToTimestamp() {
  358. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  359. }
  360. func ToUnicode(text string) string {
  361. textQuoted := strconv.QuoteToASCII(text)
  362. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  363. return textUnquoted
  364. }
  365. func VersionToInt(version string) int {
  366. version = strings.Replace(version, ".", "", -1)
  367. n, _ := strconv.Atoi(version)
  368. return n
  369. }
  370. func IsCheckInList(list []int, s int) bool {
  371. for _, v := range list {
  372. if v == s {
  373. return true
  374. }
  375. }
  376. return false
  377. }
  378. func round(num float64) int {
  379. return int(num + math.Copysign(0.5, num))
  380. }
  381. func toFixed(num float64, precision int) float64 {
  382. output := math.Pow(10, float64(precision))
  383. return float64(round(num*output)) / output
  384. }
  385. // GetWilsonScore returns Wilson Score
  386. func GetWilsonScore(p, n float64) float64 {
  387. if p == 0 && n == 0 {
  388. return 0
  389. }
  390. 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)
  391. }
  392. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  393. func ChangeWordsToNum(str string) (numStr string) {
  394. words := ([]rune)(str)
  395. num := 0
  396. n := 0
  397. for i := 0; i < len(words); i++ {
  398. word := string(words[i : i+1])
  399. switch word {
  400. case "万":
  401. if n == 0 {
  402. n = 1
  403. }
  404. n = n * 10000
  405. num = num*10000 + n
  406. n = 0
  407. case "千":
  408. if n == 0 {
  409. n = 1
  410. }
  411. n = n * 1000
  412. num += n
  413. n = 0
  414. case "百":
  415. if n == 0 {
  416. n = 1
  417. }
  418. n = n * 100
  419. num += n
  420. n = 0
  421. case "十":
  422. if n == 0 {
  423. n = 1
  424. }
  425. n = n * 10
  426. num += n
  427. n = 0
  428. case "一":
  429. n += 1
  430. case "二":
  431. n += 2
  432. case "三":
  433. n += 3
  434. case "四":
  435. n += 4
  436. case "五":
  437. n += 5
  438. case "六":
  439. n += 6
  440. case "七":
  441. n += 7
  442. case "八":
  443. n += 8
  444. case "九":
  445. n += 9
  446. case "零":
  447. default:
  448. if n > 0 {
  449. num += n
  450. n = 0
  451. }
  452. if num == 0 {
  453. numStr += word
  454. } else {
  455. numStr += strconv.Itoa(num) + word
  456. num = 0
  457. }
  458. }
  459. }
  460. if n > 0 {
  461. num += n
  462. n = 0
  463. }
  464. if num != 0 {
  465. numStr += strconv.Itoa(num)
  466. }
  467. return
  468. }
  469. func Sha1(data string) string {
  470. sha1 := sha1.New()
  471. sha1.Write([]byte(data))
  472. return hex.EncodeToString(sha1.Sum([]byte("")))
  473. }
  474. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  475. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  476. out, err := exec.Command("bash", "-c", cmd).Output()
  477. if err != nil {
  478. return
  479. }
  480. outTimes := string(out)
  481. fmt.Println("outTimes:", outTimes)
  482. if outTimes != "" {
  483. timeArr := strings.Split(outTimes, ":")
  484. h := timeArr[0]
  485. m := timeArr[1]
  486. s := timeArr[2]
  487. hInt, err := strconv.Atoi(h)
  488. if err != nil {
  489. return playSeconds, err
  490. }
  491. mInt, err := strconv.Atoi(m)
  492. if err != nil {
  493. return playSeconds, err
  494. }
  495. s = strings.Trim(s, " ")
  496. s = strings.Trim(s, "\n")
  497. sInt, err := strconv.ParseFloat(s, 64)
  498. if err != nil {
  499. return playSeconds, err
  500. }
  501. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  502. }
  503. return
  504. }
  505. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  506. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  507. tradeCode = strings.Trim(tradeCode, " ")
  508. tradeCodeInt, err := strconv.Atoi(tradeCode)
  509. if err != nil {
  510. return
  511. }
  512. tradeCodeInt = tradeCodeInt + 1
  513. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  514. return
  515. }
  516. // excel日期字段格式化 yyyy-mm-dd
  517. func ConvertToFormatDay(excelDaysString string) string {
  518. // 2006-01-02 距离 1900-01-01的天数
  519. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  520. curDiffDay := excelDaysString
  521. b, _ := strconv.Atoi(curDiffDay)
  522. // 获取excel的日期距离2006-01-02的天数
  523. realDiffDay := b - baseDiffDay
  524. //fmt.Println("realDiffDay:",realDiffDay)
  525. // 距离2006-01-02 秒数
  526. realDiffSecond := realDiffDay * 24 * 3600
  527. //fmt.Println("realDiffSecond:",realDiffSecond)
  528. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  529. baseOriginSecond := 1136185445
  530. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  531. return resultTime
  532. }
  533. func CheckPwd(pwd string) bool {
  534. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  535. reg := regexp.MustCompile(compile)
  536. flag := reg.MatchString(pwd)
  537. return flag
  538. }
  539. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  540. // 数字月份必须前置补零
  541. if len(myMonth) == 1 {
  542. myMonth = "0" + myMonth
  543. }
  544. yInt, _ := strconv.Atoi(myYear)
  545. timeLayout := "2006-01-02 15:04:05"
  546. loc, _ := time.LoadLocation("Local")
  547. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  548. newMonth := theTime.Month()
  549. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  550. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  551. return t1, t2
  552. }
  553. // 移除字符串中的空格
  554. func TrimStr(str string) (str2 string) {
  555. return strings.Replace(str, " ", "", -1)
  556. }
  557. // 字符串转换为time
  558. func StrTimeToTime(strTime string) time.Time {
  559. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  560. loc, _ := time.LoadLocation("Local") //重要:获取时区
  561. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  562. return resultTime
  563. }
  564. // 字符串类型时间转周几
  565. func StrDateTimeToWeek(strTime string) string {
  566. var WeekDayMap = map[string]string{
  567. "Monday": "周一",
  568. "Tuesday": "周二",
  569. "Wednesday": "周三",
  570. "Thursday": "周四",
  571. "Friday": "周五",
  572. "Saturday": "周六",
  573. "Sunday": "周日",
  574. }
  575. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  576. startday, _ := time.Parse("2006-01-02", ctime)
  577. staweek_int := startday.Weekday().String()
  578. return WeekDayMap[staweek_int]
  579. }
  580. // 时间格式转年月日字符串
  581. func TimeToStrYmd(time2 time.Time) string {
  582. var Ymd string
  583. year := time2.Year()
  584. month := time2.Format("1")
  585. day1 := time.Now().Day()
  586. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  587. return Ymd
  588. }
  589. // 时间格式去掉时分秒
  590. func TimeRemoveHms(strTime string) string {
  591. var Ymd string
  592. var resultTime = StrTimeToTime(strTime)
  593. year := resultTime.Year()
  594. month := resultTime.Format("01")
  595. day1 := resultTime.Day()
  596. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  597. return Ymd
  598. }
  599. // 文章上一次编辑时间
  600. func ArticleLastTime(strTime string) string {
  601. var newTime string
  602. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  603. diffTime := time.Now().Unix() - stamp.Unix()
  604. if diffTime <= 60 {
  605. newTime = "当前"
  606. } else if diffTime < 60*60 {
  607. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  608. } else if diffTime < 24*60*60 {
  609. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  610. } else if diffTime < 30*24*60*60 {
  611. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  612. } else if diffTime < 12*30*24*60*60 {
  613. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  614. } else {
  615. newTime = "1年前"
  616. }
  617. return newTime
  618. }
  619. // 人民币小写转大写
  620. func ConvertNumToCny(num float64) (str string, err error) {
  621. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  622. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  623. // log.Println(sliceUnit[:len(sliceUnit)-2])
  624. s := sliceUnit[len(sliceUnit)-len(strNum):]
  625. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  626. for k, v := range strNum[:] {
  627. str = str + upperDigitUnit[string(v)] + s[k]
  628. }
  629. reg, err := regexp.Compile(`零角零分$`)
  630. str = reg.ReplaceAllString(str, "整")
  631. reg, err = regexp.Compile(`零角`)
  632. str = reg.ReplaceAllString(str, "零")
  633. reg, err = regexp.Compile(`零分$`)
  634. str = reg.ReplaceAllString(str, "整")
  635. reg, err = regexp.Compile(`零[仟佰拾]`)
  636. str = reg.ReplaceAllString(str, "零")
  637. reg, err = regexp.Compile(`零{2,}`)
  638. str = reg.ReplaceAllString(str, "零")
  639. reg, err = regexp.Compile(`零亿`)
  640. str = reg.ReplaceAllString(str, "亿")
  641. reg, err = regexp.Compile(`零万`)
  642. str = reg.ReplaceAllString(str, "万")
  643. reg, err = regexp.Compile(`零*元`)
  644. str = reg.ReplaceAllString(str, "元")
  645. reg, err = regexp.Compile(`亿零{0, 3}万`)
  646. str = reg.ReplaceAllString(str, "^元")
  647. reg, err = regexp.Compile(`零元`)
  648. str = reg.ReplaceAllString(str, "零")
  649. return
  650. }
  651. // GetNowWeekMonday 获取本周周一的时间
  652. func GetNowWeekMonday() time.Time {
  653. offset := int(time.Monday - time.Now().Weekday())
  654. mondayTime := time.Now().AddDate(0, 0, offset)
  655. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  656. return mondayTime
  657. }
  658. // GetNowWeekLastDay 获取本周最后一天的时间
  659. func GetNowWeekLastDay() time.Time {
  660. offset := int(time.Monday - time.Now().Weekday())
  661. firstDayTime := time.Now().AddDate(0, 0, offset)
  662. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  663. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  664. return lastDayTime
  665. }
  666. // GetNowMonthFirstDay 获取本月第一天的时间
  667. func GetNowMonthFirstDay() time.Time {
  668. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  669. return nowMonthFirstDay
  670. }
  671. // GetNowMonthLastDay 获取本月最后一天的时间
  672. func GetNowMonthLastDay() time.Time {
  673. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  674. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  675. return nowMonthLastDay
  676. }
  677. // GetNowQuarterFirstDay 获取本季度第一天的时间
  678. func GetNowQuarterFirstDay() time.Time {
  679. month := int(time.Now().Month())
  680. var nowQuarterFirstDay time.Time
  681. if month >= 1 && month <= 3 {
  682. //1月1号
  683. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  684. } else if month >= 4 && month <= 6 {
  685. //4月1号
  686. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  687. } else if month >= 7 && month <= 9 {
  688. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  689. } else {
  690. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  691. }
  692. return nowQuarterFirstDay
  693. }
  694. // GetNowQuarterLastDay 获取本季度最后一天的时间
  695. func GetNowQuarterLastDay() time.Time {
  696. month := int(time.Now().Month())
  697. var nowQuarterLastDay time.Time
  698. if month >= 1 && month <= 3 {
  699. //03-31 23:59:59
  700. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  701. } else if month >= 4 && month <= 6 {
  702. //06-30 23:59:59
  703. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  704. } else if month >= 7 && month <= 9 {
  705. //09-30 23:59:59
  706. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  707. } else {
  708. //12-31 23:59:59
  709. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  710. }
  711. return nowQuarterLastDay
  712. }
  713. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  714. func GetNowHalfYearFirstDay() time.Time {
  715. month := int(time.Now().Month())
  716. var nowHalfYearLastDay time.Time
  717. if month >= 1 && month <= 6 {
  718. //03-31 23:59:59
  719. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  720. } else {
  721. //12-31 23:59:59
  722. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  723. }
  724. return nowHalfYearLastDay
  725. }
  726. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  727. func GetNowHalfYearLastDay() time.Time {
  728. month := int(time.Now().Month())
  729. var nowHalfYearLastDay time.Time
  730. if month >= 1 && month <= 6 {
  731. //03-31 23:59:59
  732. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  733. } else {
  734. //12-31 23:59:59
  735. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  736. }
  737. return nowHalfYearLastDay
  738. }
  739. // GetNowYearFirstDay 获取当前年的最后一天的时间
  740. func GetNowYearFirstDay() time.Time {
  741. //12-31 23:59:59
  742. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  743. return nowYearFirstDay
  744. }
  745. // GetNowYearLastDay 获取当前年的最后一天的时间
  746. func GetNowYearLastDay() time.Time {
  747. //12-31 23:59:59
  748. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  749. return nowYearLastDay
  750. }
  751. // CalculationDate 计算两个日期之间相差n年m月y天
  752. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  753. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  754. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  755. numYear := endDate.Year() - startDate.Year()
  756. numMonth := int(endDate.Month()) - int(startDate.Month())
  757. numDay := 0
  758. //获取截止月的总天数
  759. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  760. //获取截止月的前一个月
  761. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  762. //获取截止日期的上一个月的总天数
  763. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  764. //获取开始日期的的月份总天数
  765. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  766. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  767. if endDate.Day() == endDateDays {
  768. numDay = startDateMonthDays - startDate.Day() + 1
  769. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  770. if numDay == startDateMonthDays {
  771. numMonth++
  772. numDay = 0
  773. //超过月份了,那么年份加1
  774. if numMonth == 12 {
  775. numYear++
  776. numMonth = 0
  777. }
  778. }
  779. } else {
  780. numDay = endDate.Day() - startDate.Day() + 1
  781. }
  782. //天数小于0,那么向月份借一位
  783. if numDay < 0 {
  784. //向上一个月借一个月的天数
  785. numDay += endDatePrevMonthDays
  786. //总月份减去一个月
  787. numMonth = numMonth - 1
  788. }
  789. //月份小于0,那么向年份借一位
  790. if numMonth < 0 {
  791. //向上一个年借12个月
  792. numMonth += 12
  793. //总年份减去一年
  794. numYear = numYear - 1
  795. }
  796. if numYear < 0 {
  797. err = errors.New("日期异常")
  798. return
  799. }
  800. if numYear > 0 {
  801. beetweenDay += fmt.Sprint(numYear, "年")
  802. }
  803. if numMonth > 0 {
  804. beetweenDay += fmt.Sprint(numMonth, "个月")
  805. }
  806. if numDay > 0 {
  807. beetweenDay += fmt.Sprint(numDay, "天")
  808. }
  809. return
  810. }
  811. // getMonthDay 获取某年某月有多少天
  812. func getMonthDay(year, month int) (days int) {
  813. if month != 2 {
  814. if month == 4 || month == 6 || month == 9 || month == 11 {
  815. days = 30
  816. } else {
  817. days = 31
  818. }
  819. } else {
  820. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  821. days = 29
  822. } else {
  823. days = 28
  824. }
  825. }
  826. return
  827. }
  828. // GetOrmInReplace 获取orm的in查询替换?的方法
  829. func GetOrmInReplace(num int) string {
  830. template := make([]string, num)
  831. for i := 0; i < num; i++ {
  832. template[i] = "?"
  833. }
  834. return strings.Join(template, ",")
  835. }
  836. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  837. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  838. for _, id := range idIntList {
  839. if id == searchId {
  840. has = true
  841. return
  842. }
  843. }
  844. return
  845. }
  846. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  847. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  848. for _, id := range idStrList {
  849. if id == searchId {
  850. has = true
  851. return
  852. }
  853. }
  854. return
  855. }
  856. // RangeRand 取区间随机数
  857. func RangeRand(min, max int64) int64 {
  858. if min > max {
  859. return max
  860. }
  861. if min < 0 {
  862. f64Min := math.Abs(float64(min))
  863. i64Min := int64(f64Min)
  864. result, _ := cryRand.Int(cryRand.Reader, big.NewInt(max+1+i64Min))
  865. return result.Int64() - i64Min
  866. } else {
  867. result, _ := cryRand.Int(cryRand.Reader, big.NewInt(max-min+1))
  868. return min + result.Int64()
  869. }
  870. }
  871. func GetLocalIP() (ip string, err error) {
  872. addrs, err := net.InterfaceAddrs()
  873. if err != nil {
  874. return
  875. }
  876. for _, addr := range addrs {
  877. ipAddr, ok := addr.(*net.IPNet)
  878. if !ok {
  879. continue
  880. }
  881. if ipAddr.IP.IsLoopback() {
  882. continue
  883. }
  884. if !ipAddr.IP.IsGlobalUnicast() {
  885. continue
  886. }
  887. return ipAddr.IP.String(), nil
  888. }
  889. return
  890. }
  891. // HTTP: post请求参数
  892. //
  893. // {
  894. // "A" : 10086,
  895. // "B" : "请求信息"
  896. // }
  897. type RequestParam struct {
  898. A int `json:"A"`
  899. B string `json:"B"`
  900. }
  901. // HTTP返回Body
  902. type HTTPRspBody struct {
  903. Result Results `json:"Result"`
  904. }
  905. type Results struct {
  906. RequestID string `json:"Result"`
  907. HasError bool `json:"HasError"`
  908. ResponseItems ErrorMsg `json:"ResponseItems"`
  909. }
  910. type ErrorMsg struct {
  911. ErrorMsg string `json:"ErrorMsg"`
  912. }
  913. // 修改供应商信息
  914. func HttpPost(url string, reqParam string, headersParams map[string]string) ([]byte, error) {
  915. var (
  916. err error
  917. )
  918. // 准备: HTTP请求
  919. reqBody := strings.NewReader(reqParam)
  920. httpReq, err := http.NewRequest("POST", url, reqBody)
  921. if err != nil {
  922. fmt.Printf("NewRequest fail, url: %s, reqBody: %s, err: %v", url, reqBody, err)
  923. return nil, err
  924. }
  925. for k, v := range headersParams {
  926. httpReq.Header.Set(k, v)
  927. }
  928. //httpReq.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
  929. jar, err := cookiejar.New(nil)
  930. if err != nil {
  931. panic(err)
  932. }
  933. //httpReq.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
  934. client := &http.Client{Jar: jar}
  935. // DO: HTTP请求
  936. httpRsp, err := client.Do(httpReq)
  937. if err != nil {
  938. fmt.Printf("do http fail, url: %s, reqBody: %s, err:%v", url, reqBody, err)
  939. return nil, err
  940. }
  941. defer httpRsp.Body.Close()
  942. // Read: HTTP结果
  943. b, err := ioutil.ReadAll(httpRsp.Body)
  944. if err != nil {
  945. fmt.Printf("ReadAll failed, url: %s, reqBody: %s, err: %v", url, reqBody, err)
  946. return nil, err
  947. }
  948. // unmarshal: 解析HTTP返回的结果
  949. // body: {"Result":{"RequestId":"12131","HasError":true,"ResponseItems":{"ErrorMsg":"错误信息"}}}
  950. return b, err
  951. }
  952. func HttpGet(reqUrl, payload string) (err error) {
  953. client := &http.Client{}
  954. req, err := http.NewRequest("GET", reqUrl, strings.NewReader(payload))
  955. if err != nil {
  956. return
  957. }
  958. res, err := client.Do(req)
  959. if err != nil {
  960. return
  961. }
  962. defer res.Body.Close()
  963. _, err = ioutil.ReadAll(res.Body)
  964. if err != nil {
  965. return
  966. }
  967. Cookie := res.Header.Get("Cookie")
  968. fmt.Println(Cookie)
  969. rcookie := req.Header.Get("Cookie")
  970. fmt.Println("rcookie")
  971. fmt.Println(rcookie)
  972. //fmt.Println("body:" + string(body))
  973. cookiesArr := res.Cookies()
  974. fmt.Println("cookiesArrLen:", len(cookiesArr))
  975. for k, v := range cookiesArr {
  976. fmt.Println(k, v)
  977. }
  978. return
  979. }
  980. func ChineseToPinyin(input string) string {
  981. a := pinyin.NewArgs()
  982. var result strings.Builder
  983. for _, r := range input {
  984. if unicode.Is(unicode.Han, r) {
  985. py := pinyin.Pinyin(string(r), a)
  986. if len(py) > 0 && len(py[0]) > 0 {
  987. result.WriteString(py[0][0])
  988. }
  989. } else if unicode.IsNumber(r) || unicode.IsLetter(r) {
  990. result.WriteRune(r)
  991. }
  992. }
  993. return result.String()
  994. }
  995. func ChineseToPinyinInitials(input string) string {
  996. a := pinyin.NewArgs()
  997. a.Style = pinyin.FirstLetter // 设置风格为首字母
  998. var result strings.Builder
  999. for _, r := range input {
  1000. if unicode.Is(unicode.Han, r) {
  1001. py := pinyin.Pinyin(string(r), a)
  1002. if len(py) > 0 && len(py[0]) > 0 {
  1003. result.WriteString(py[0][0])
  1004. }
  1005. } else if unicode.IsNumber(r) || unicode.IsLetter(r) {
  1006. result.WriteRune(r)
  1007. }
  1008. }
  1009. return result.String()
  1010. }