common.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "fmt"
  10. "image"
  11. "image/png"
  12. "io"
  13. "math"
  14. "math/rand"
  15. "net"
  16. "net/http"
  17. "os"
  18. "os/exec"
  19. "path"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "time"
  24. )
  25. // 随机数种子
  26. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  27. func GetRandString(size int) string {
  28. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  29. randomSb := ""
  30. digitSize := len(allLetterDigit)
  31. for i := 0; i < size; i++ {
  32. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  33. }
  34. return randomSb
  35. }
  36. func GetRandStringNoSpecialChar(size int) string {
  37. 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"}
  38. randomSb := ""
  39. digitSize := len(allLetterDigit)
  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. // 获取数字随机字符
  69. func GetRandDigit(n int) string {
  70. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  71. }
  72. // 获取随机数
  73. func GetRandNumber(n int) int {
  74. return rnd.Intn(n)
  75. }
  76. func GetRandInt(min, max int) int {
  77. if min >= max || min == 0 || max == 0 {
  78. return max
  79. }
  80. return rand.Intn(max-min) + min
  81. }
  82. func GetToday(format string) string {
  83. today := time.Now().Format(format)
  84. return today
  85. }
  86. // 获取今天剩余秒数
  87. func GetTodayLastSecond() time.Duration {
  88. today := GetToday(FormatDate) + " 23:59:59"
  89. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  90. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  91. }
  92. // 处理出生日期函数
  93. func GetBrithDate(idcard string) string {
  94. l := len(idcard)
  95. var s string
  96. if l == 15 {
  97. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  98. return s
  99. }
  100. if l == 18 {
  101. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  102. return s
  103. }
  104. return GetToday(FormatDate)
  105. }
  106. // 处理性别
  107. func WhichSexByIdcard(idcard string) string {
  108. var sexs = [2]string{"女", "男"}
  109. length := len(idcard)
  110. if length == 18 {
  111. sex, _ := strconv.Atoi(string(idcard[16]))
  112. return sexs[sex%2]
  113. } else if length == 15 {
  114. sex, _ := strconv.Atoi(string(idcard[14]))
  115. return sexs[sex%2]
  116. }
  117. return "男"
  118. }
  119. // 截取小数点后几位
  120. func SubFloatToString(f float64, m int) string {
  121. n := strconv.FormatFloat(f, 'f', -1, 64)
  122. if n == "" {
  123. return ""
  124. }
  125. if m >= len(n) {
  126. return n
  127. }
  128. newn := strings.Split(n, ".")
  129. if m == 0 {
  130. return newn[0]
  131. }
  132. if len(newn) < 2 || m >= len(newn[1]) {
  133. return n
  134. }
  135. return newn[0] + "." + newn[1][:m]
  136. }
  137. // 截取小数点后几位
  138. func SubFloatToFloat(f float64, m int) float64 {
  139. newn := SubFloatToString(f, m)
  140. newf, _ := strconv.ParseFloat(newn, 64)
  141. return newf
  142. }
  143. // 截取小数点后几位
  144. func SubFloatToFloatStr(f float64, m int) string {
  145. newn := SubFloatToString(f, m)
  146. return newn
  147. }
  148. // 获取相差时间-年
  149. func GetYearDiffer(start_time, end_time string) int {
  150. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  151. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  152. age := t2.Year() - t1.Year()
  153. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  154. age--
  155. }
  156. return age
  157. }
  158. // 获取相差时间-秒
  159. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  160. diff := end_time.Unix() - start_time.Unix()
  161. return diff
  162. }
  163. func FixFloat(f float64, m int) float64 {
  164. newn := SubFloatToString(f+0.00000001, m)
  165. newf, _ := strconv.ParseFloat(newn, 64)
  166. return newf
  167. }
  168. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  169. func StrListToString(strList []string) (str string) {
  170. if len(strList) > 0 {
  171. for k, v := range strList {
  172. if k == 0 {
  173. str = v
  174. } else {
  175. str = str + "," + v
  176. }
  177. }
  178. return
  179. }
  180. return ""
  181. }
  182. // 数据没有记录
  183. func ErrNoRow() string {
  184. return "<QuerySeter> no row found"
  185. }
  186. // 校验邮箱格式
  187. func ValidateEmailFormatat(email string) bool {
  188. reg := regexp.MustCompile(RegularEmail)
  189. return reg.MatchString(email)
  190. }
  191. // 验证是否是手机号
  192. func ValidateMobileFormatat(mobileNum string) bool {
  193. reg := regexp.MustCompile(RegularMobile)
  194. return reg.MatchString(mobileNum)
  195. }
  196. // 判断文件是否存在
  197. func FileIsExist(filePath string) bool {
  198. _, err := os.Stat(filePath)
  199. return err == nil || os.IsExist(err)
  200. }
  201. // 获取图片扩展名
  202. func GetImgExt(file string) (ext string, err error) {
  203. var headerByte []byte
  204. headerByte = make([]byte, 8)
  205. fd, err := os.Open(file)
  206. if err != nil {
  207. return "", err
  208. }
  209. defer fd.Close()
  210. _, err = fd.Read(headerByte)
  211. if err != nil {
  212. return "", err
  213. }
  214. xStr := fmt.Sprintf("%x", headerByte)
  215. switch {
  216. case xStr == "89504e470d0a1a0a":
  217. ext = ".png"
  218. case xStr == "0000010001002020":
  219. ext = ".ico"
  220. case xStr == "0000020001002020":
  221. ext = ".cur"
  222. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  223. ext = ".gif"
  224. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  225. ext = ".tga"
  226. case xStr[:8] == "464f524d":
  227. ext = ".iff"
  228. case xStr[:8] == "52494646":
  229. ext = ".ani"
  230. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  231. ext = ".tiff"
  232. case xStr[:4] == "424d":
  233. ext = ".bmp"
  234. case xStr[:4] == "ffd8":
  235. ext = ".jpg"
  236. case xStr[:2] == "0a":
  237. ext = ".pcx"
  238. default:
  239. ext = ""
  240. }
  241. return ext, nil
  242. }
  243. // 保存图片
  244. func SaveImage(path string, img image.Image) (err error) {
  245. //需要保持的文件
  246. imgfile, err := os.Create(path)
  247. defer imgfile.Close()
  248. // 以PNG格式保存文件
  249. err = png.Encode(imgfile, img)
  250. return err
  251. }
  252. // DownloadImage 下载图片
  253. func DownloadImage(imgUrl string) (filePath string, err error) {
  254. imgPath := "./static/imgs/"
  255. if !FileIsExist(imgPath) {
  256. err = os.MkdirAll(imgPath, 0777)
  257. if err != nil {
  258. return
  259. }
  260. }
  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. defer func() {
  276. file.Close()
  277. }()
  278. // 获得文件的writer对象
  279. writer := bufio.NewWriter(file)
  280. written, _ := io.Copy(writer, reader)
  281. fmt.Printf("Total length: %d \n", written)
  282. return
  283. }
  284. // DownloadFile 下载文件
  285. func DownloadFile(fileUrl, fileDir string) (filePath string, err error) {
  286. filePathDir := "./static/imgs/"
  287. if fileDir != `` {
  288. err = os.MkdirAll(fileDir, 0766)
  289. if err != nil {
  290. return
  291. }
  292. filePathDir = fileDir
  293. }
  294. fileName := path.Base(fileUrl)
  295. res, err := http.Get(fileUrl)
  296. if err != nil {
  297. fmt.Println("A error occurred!")
  298. return
  299. }
  300. defer res.Body.Close()
  301. // 获得get请求响应的reader对象
  302. reader := bufio.NewReaderSize(res.Body, 32*1024)
  303. filePath = filePathDir + GetRandStringNoSpecialChar(4) + fileName
  304. file, err := os.Create(filePath)
  305. if err != nil {
  306. return
  307. }
  308. defer func() {
  309. file.Close()
  310. }()
  311. // 获得文件的writer对象
  312. writer := bufio.NewWriter(file)
  313. _, _ = io.Copy(writer, reader)
  314. //fmt.Printf("Total length: %d \n", written)
  315. return
  316. }
  317. // 保存base64数据为文件
  318. func SaveBase64ToFile(content, path string) error {
  319. data, err := base64.StdEncoding.DecodeString(content)
  320. if err != nil {
  321. return err
  322. }
  323. f, err := os.Create(path)
  324. defer f.Close()
  325. if err != nil {
  326. return err
  327. }
  328. f.Write(data)
  329. return nil
  330. }
  331. // 保存base64数据为文件
  332. func SaveToFile(content, path string) error {
  333. f, err := os.Create(path)
  334. defer f.Close()
  335. if err != nil {
  336. return err
  337. }
  338. f.Write([]byte(content))
  339. return nil
  340. }
  341. func SaveBase64ToFileBySeek(content, path string) (err error) {
  342. data, err := base64.StdEncoding.DecodeString(content)
  343. exist, err := PathExists(path)
  344. if err != nil {
  345. return
  346. }
  347. if !exist {
  348. f, err := os.Create(path)
  349. if err != nil {
  350. return err
  351. }
  352. n, _ := f.Seek(0, 2)
  353. // 从末尾的偏移量开始写入内容
  354. _, err = f.WriteAt([]byte(data), n)
  355. defer f.Close()
  356. } else {
  357. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  358. if err != nil {
  359. return err
  360. }
  361. n, _ := f.Seek(0, 2)
  362. // 从末尾的偏移量开始写入内容
  363. _, err = f.WriteAt([]byte(data), n)
  364. defer f.Close()
  365. }
  366. return nil
  367. }
  368. func PathExists(path string) (bool, error) {
  369. _, err := os.Stat(path)
  370. if err == nil {
  371. return true, nil
  372. }
  373. if os.IsNotExist(err) {
  374. return false, nil
  375. }
  376. return false, err
  377. }
  378. func StartIndex(page, pagesize int) int {
  379. if page > 1 {
  380. return (page - 1) * pagesize
  381. }
  382. return 0
  383. }
  384. func PageCount(count, pagesize int) int {
  385. if count%pagesize > 0 {
  386. return count/pagesize + 1
  387. } else {
  388. return count / pagesize
  389. }
  390. }
  391. func TrimHtml(src string) string {
  392. //将HTML标签全转换成小写
  393. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  394. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  395. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  396. src = re.ReplaceAllString(src, "[图片]")
  397. re, _ = regexp.Compile("class[\\S\\s]+?>")
  398. src = re.ReplaceAllString(src, "")
  399. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  400. src = re.ReplaceAllString(src, "")
  401. return strings.TrimSpace(src)
  402. }
  403. //1556164246 -> 2019-04-25 03:50:46 +0000
  404. //timestamp
  405. func TimeToTimestamp() {
  406. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  407. }
  408. func ToUnicode(text string) string {
  409. textQuoted := strconv.QuoteToASCII(text)
  410. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  411. return textUnquoted
  412. }
  413. func VersionToInt(version string) int {
  414. version = strings.Replace(version, ".", "", -1)
  415. n, _ := strconv.Atoi(version)
  416. return n
  417. }
  418. func IsCheckInList(list []int, s int) bool {
  419. for _, v := range list {
  420. if v == s {
  421. return true
  422. }
  423. }
  424. return false
  425. }
  426. func round(num float64) int {
  427. return int(num + math.Copysign(0.5, num))
  428. }
  429. func toFixed(num float64, precision int) float64 {
  430. output := math.Pow(10, float64(precision))
  431. return float64(round(num*output)) / output
  432. }
  433. // GetWilsonScore returns Wilson Score
  434. func GetWilsonScore(p, n float64) float64 {
  435. if p == 0 && n == 0 {
  436. return 0
  437. }
  438. 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)
  439. }
  440. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  441. func ChangeWordsToNum(str string) (numStr string) {
  442. words := ([]rune)(str)
  443. num := 0
  444. n := 0
  445. for i := 0; i < len(words); i++ {
  446. word := string(words[i : i+1])
  447. switch word {
  448. case "万":
  449. if n == 0 {
  450. n = 1
  451. }
  452. n = n * 10000
  453. num = num*10000 + n
  454. n = 0
  455. case "千":
  456. if n == 0 {
  457. n = 1
  458. }
  459. n = n * 1000
  460. num += n
  461. n = 0
  462. case "百":
  463. if n == 0 {
  464. n = 1
  465. }
  466. n = n * 100
  467. num += n
  468. n = 0
  469. case "十":
  470. if n == 0 {
  471. n = 1
  472. }
  473. n = n * 10
  474. num += n
  475. n = 0
  476. case "一":
  477. n += 1
  478. case "二":
  479. n += 2
  480. case "三":
  481. n += 3
  482. case "四":
  483. n += 4
  484. case "五":
  485. n += 5
  486. case "六":
  487. n += 6
  488. case "七":
  489. n += 7
  490. case "八":
  491. n += 8
  492. case "九":
  493. n += 9
  494. case "零":
  495. default:
  496. if n > 0 {
  497. num += n
  498. n = 0
  499. }
  500. if num == 0 {
  501. numStr += word
  502. } else {
  503. numStr += strconv.Itoa(num) + word
  504. num = 0
  505. }
  506. }
  507. }
  508. if n > 0 {
  509. num += n
  510. n = 0
  511. }
  512. if num != 0 {
  513. numStr += strconv.Itoa(num)
  514. }
  515. return
  516. }
  517. func Sha1(data string) string {
  518. sha1 := sha1.New()
  519. sha1.Write([]byte(data))
  520. return hex.EncodeToString(sha1.Sum([]byte("")))
  521. }
  522. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  523. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  524. out, err := exec.Command("bash", "-c", cmd).Output()
  525. if err != nil {
  526. return
  527. }
  528. outTimes := string(out)
  529. fmt.Println("outTimes:", outTimes)
  530. if outTimes != "" {
  531. timeArr := strings.Split(outTimes, ":")
  532. h := timeArr[0]
  533. m := timeArr[1]
  534. s := timeArr[2]
  535. hInt, err := strconv.Atoi(h)
  536. if err != nil {
  537. return playSeconds, err
  538. }
  539. mInt, err := strconv.Atoi(m)
  540. if err != nil {
  541. return playSeconds, err
  542. }
  543. s = strings.Trim(s, " ")
  544. s = strings.Trim(s, "\n")
  545. sInt, err := strconv.ParseFloat(s, 64)
  546. if err != nil {
  547. return playSeconds, err
  548. }
  549. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  550. }
  551. return
  552. }
  553. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  554. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  555. tradeCode = strings.Trim(tradeCode, " ")
  556. tradeCodeInt, err := strconv.Atoi(tradeCode)
  557. if err != nil {
  558. return
  559. }
  560. tradeCodeInt = tradeCodeInt + 1
  561. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  562. return
  563. }
  564. // excel日期字段格式化 yyyy-mm-dd
  565. func ConvertToFormatDay(excelDaysString string) string {
  566. // 2006-01-02 距离 1900-01-01的天数
  567. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  568. curDiffDay := excelDaysString
  569. b, _ := strconv.Atoi(curDiffDay)
  570. // 获取excel的日期距离2006-01-02的天数
  571. realDiffDay := b - baseDiffDay
  572. //fmt.Println("realDiffDay:",realDiffDay)
  573. // 距离2006-01-02 秒数
  574. realDiffSecond := realDiffDay * 24 * 3600
  575. //fmt.Println("realDiffSecond:",realDiffSecond)
  576. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  577. baseOriginSecond := 1136185445
  578. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  579. return resultTime
  580. }
  581. func CheckPwd(pwd string) bool {
  582. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  583. reg := regexp.MustCompile(compile)
  584. flag := reg.MatchString(pwd)
  585. return flag
  586. }
  587. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  588. // 数字月份必须前置补零
  589. if len(myMonth) == 1 {
  590. myMonth = "0" + myMonth
  591. }
  592. yInt, _ := strconv.Atoi(myYear)
  593. timeLayout := "2006-01-02 15:04:05"
  594. loc, _ := time.LoadLocation("Local")
  595. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  596. newMonth := theTime.Month()
  597. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  598. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  599. return t1, t2
  600. }
  601. // 移除字符串中的空格
  602. func TrimStr(str string) (str2 string) {
  603. return strings.Replace(str, " ", "", -1)
  604. }
  605. // 字符串转换为time
  606. func StrTimeToTime(strTime string) time.Time {
  607. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  608. loc, _ := time.LoadLocation("Local") //重要:获取时区
  609. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  610. return resultTime
  611. }
  612. // 字符串类型时间转周几
  613. func StrDateTimeToWeek(strTime string) string {
  614. var WeekDayMap = map[string]string{
  615. "Monday": "周一",
  616. "Tuesday": "周二",
  617. "Wednesday": "周三",
  618. "Thursday": "周四",
  619. "Friday": "周五",
  620. "Saturday": "周六",
  621. "Sunday": "周日",
  622. }
  623. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  624. startday, _ := time.Parse("2006-01-02", ctime)
  625. staweek_int := startday.Weekday().String()
  626. return WeekDayMap[staweek_int]
  627. }
  628. // 时间格式转年月日字符串
  629. func TimeToStrYmd(time2 time.Time) string {
  630. var Ymd string
  631. year := time2.Year()
  632. month := time2.Format("1")
  633. day1 := time.Now().Day()
  634. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  635. return Ymd
  636. }
  637. // 时间格式去掉时分秒
  638. func TimeRemoveHms(strTime string) string {
  639. var Ymd string
  640. var resultTime = StrTimeToTime(strTime)
  641. year := resultTime.Year()
  642. month := resultTime.Format("01")
  643. day1 := resultTime.Day()
  644. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  645. return Ymd
  646. }
  647. // 文章上一次编辑时间
  648. func ArticleLastTime(strTime string) string {
  649. var newTime string
  650. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  651. diffTime := time.Now().Unix() - stamp.Unix()
  652. if diffTime <= 60 {
  653. newTime = "当前"
  654. } else if diffTime < 60*60 {
  655. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  656. } else if diffTime < 24*60*60 {
  657. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  658. } else if diffTime < 30*24*60*60 {
  659. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  660. } else if diffTime < 12*30*24*60*60 {
  661. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  662. } else {
  663. newTime = "1年前"
  664. }
  665. return newTime
  666. }
  667. // 人民币小写转大写
  668. func ConvertNumToCny(num float64) (str string, err error) {
  669. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  670. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  671. // log.Println(sliceUnit[:len(sliceUnit)-2])
  672. s := sliceUnit[len(sliceUnit)-len(strNum):]
  673. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  674. for k, v := range strNum[:] {
  675. str = str + upperDigitUnit[string(v)] + s[k]
  676. }
  677. reg, err := regexp.Compile(`零角零分$`)
  678. str = reg.ReplaceAllString(str, "整")
  679. reg, err = regexp.Compile(`零角`)
  680. str = reg.ReplaceAllString(str, "零")
  681. reg, err = regexp.Compile(`零分$`)
  682. str = reg.ReplaceAllString(str, "整")
  683. reg, err = regexp.Compile(`零[仟佰拾]`)
  684. str = reg.ReplaceAllString(str, "零")
  685. reg, err = regexp.Compile(`零{2,}`)
  686. str = reg.ReplaceAllString(str, "零")
  687. reg, err = regexp.Compile(`零亿`)
  688. str = reg.ReplaceAllString(str, "亿")
  689. reg, err = regexp.Compile(`零万`)
  690. str = reg.ReplaceAllString(str, "万")
  691. reg, err = regexp.Compile(`零*元`)
  692. str = reg.ReplaceAllString(str, "元")
  693. reg, err = regexp.Compile(`亿零{0, 3}万`)
  694. str = reg.ReplaceAllString(str, "^元")
  695. reg, err = regexp.Compile(`零元`)
  696. str = reg.ReplaceAllString(str, "零")
  697. return
  698. }
  699. func GetLocalIP() (ip string, err error) {
  700. addrs, err := net.InterfaceAddrs()
  701. if err != nil {
  702. return
  703. }
  704. for _, addr := range addrs {
  705. ipAddr, ok := addr.(*net.IPNet)
  706. if !ok {
  707. continue
  708. }
  709. if ipAddr.IP.IsLoopback() {
  710. continue
  711. }
  712. if !ipAddr.IP.IsGlobalUnicast() {
  713. continue
  714. }
  715. return ipAddr.IP.String(), nil
  716. }
  717. return
  718. }
  719. func ExtractDataFields(input string) []string {
  720. re := regexp.MustCompile(`{{(.*?)\.DATA}}`)
  721. matches := re.FindAllStringSubmatch(input, -1)
  722. var result []string
  723. for _, match := range matches {
  724. if len(match) > 1 {
  725. result = append(result, match[1])
  726. }
  727. }
  728. return result
  729. }