common.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "image"
  10. "image/png"
  11. "math"
  12. "math/rand"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  22. func GetRandString(size int) string {
  23. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  24. randomSb := ""
  25. digitSize := len(allLetterDigit)
  26. for i := 0; i < size; i++ {
  27. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  28. }
  29. return randomSb
  30. }
  31. func GetRandStringNoSpecialChar(size int) string {
  32. 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"}
  33. randomSb := ""
  34. digitSize := len(allLetterDigit)
  35. for i := 0; i < size; i++ {
  36. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  37. }
  38. return randomSb
  39. }
  40. func StringsToJSON(str string) string {
  41. rs := []rune(str)
  42. jsons := ""
  43. for _, r := range rs {
  44. rint := int(r)
  45. if rint < 128 {
  46. jsons += string(r)
  47. } else {
  48. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  49. }
  50. }
  51. return jsons
  52. }
  53. func ToString(v interface{}) string {
  54. data, _ := json.Marshal(v)
  55. return string(data)
  56. }
  57. func MD5(data string) string {
  58. m := md5.Sum([]byte(data))
  59. return hex.EncodeToString(m[:])
  60. }
  61. func GetRandDigit(n int) string {
  62. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  63. }
  64. func GetRandNumber(n int) int {
  65. return rnd.Intn(n)
  66. }
  67. func GetRandInt(min, max int) int {
  68. if min >= max || min == 0 || max == 0 {
  69. return max
  70. }
  71. return rand.Intn(max-min) + min
  72. }
  73. func GetToday(format string) string {
  74. today := time.Now().Format(format)
  75. return today
  76. }
  77. func GetTodayLastSecond() time.Duration {
  78. today := GetToday(FormatDate) + " 23:59:59"
  79. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  80. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  81. }
  82. func GetBrithDate(idcard string) string {
  83. l := len(idcard)
  84. var s string
  85. if l == 15 {
  86. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  87. return s
  88. }
  89. if l == 18 {
  90. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  91. return s
  92. }
  93. return GetToday(FormatDate)
  94. }
  95. func WhichSexByIdcard(idcard string) string {
  96. var sexs = [2]string{"女", "男"}
  97. length := len(idcard)
  98. if length == 18 {
  99. sex, _ := strconv.Atoi(string(idcard[16]))
  100. return sexs[sex%2]
  101. } else if length == 15 {
  102. sex, _ := strconv.Atoi(string(idcard[14]))
  103. return sexs[sex%2]
  104. }
  105. return "男"
  106. }
  107. func SubFloatToString(f float64, m int) string {
  108. n := strconv.FormatFloat(f, 'f', -1, 64)
  109. if n == "" {
  110. return ""
  111. }
  112. if m >= len(n) {
  113. return n
  114. }
  115. newn := strings.Split(n, ".")
  116. if m == 0 {
  117. return newn[0]
  118. }
  119. if len(newn) < 2 || m >= len(newn[1]) {
  120. return n
  121. }
  122. return newn[0] + "." + newn[1][:m]
  123. }
  124. func SubFloatToFloat(f float64, m int) float64 {
  125. newn := SubFloatToString(f, m)
  126. newf, _ := strconv.ParseFloat(newn, 64)
  127. return newf
  128. }
  129. func GetYearDiffer(start_time, end_time string) int {
  130. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  131. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  132. age := t2.Year() - t1.Year()
  133. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  134. age--
  135. }
  136. return age
  137. }
  138. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  139. diff := end_time.Unix() - start_time.Unix()
  140. return diff
  141. }
  142. func FixFloat(f float64, m int) float64 {
  143. newn := SubFloatToString(f+0.00000001, m)
  144. newf, _ := strconv.ParseFloat(newn, 64)
  145. return newf
  146. }
  147. func StrListToString(strList []string) (str string) {
  148. if len(strList) > 0 {
  149. for k, v := range strList {
  150. if k == 0 {
  151. str = v
  152. } else {
  153. str = str + "," + v
  154. }
  155. }
  156. return
  157. }
  158. return ""
  159. }
  160. func ErrNoRow() string {
  161. return "<QuerySeter> no row found"
  162. }
  163. func ValidateEmailFormatat(email string) bool {
  164. reg := regexp.MustCompile(RegularEmail)
  165. return reg.MatchString(email)
  166. }
  167. func ValidateMobileFormatat(mobileNum string) bool {
  168. reg := regexp.MustCompile(RegularMobile)
  169. return reg.MatchString(mobileNum)
  170. }
  171. func FileIsExist(filePath string) bool {
  172. _, err := os.Stat(filePath)
  173. return err == nil || os.IsExist(err)
  174. }
  175. func GetImgExt(file string) (ext string, err error) {
  176. var headerByte []byte
  177. headerByte = make([]byte, 8)
  178. fd, err := os.Open(file)
  179. if err != nil {
  180. return "", err
  181. }
  182. defer fd.Close()
  183. _, err = fd.Read(headerByte)
  184. if err != nil {
  185. return "", err
  186. }
  187. xStr := fmt.Sprintf("%x", headerByte)
  188. switch {
  189. case xStr == "89504e470d0a1a0a":
  190. ext = ".png"
  191. case xStr == "0000010001002020":
  192. ext = ".ico"
  193. case xStr == "0000020001002020":
  194. ext = ".cur"
  195. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  196. ext = ".gif"
  197. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  198. ext = ".tga"
  199. case xStr[:8] == "464f524d":
  200. ext = ".iff"
  201. case xStr[:8] == "52494646":
  202. ext = ".ani"
  203. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  204. ext = ".tiff"
  205. case xStr[:4] == "424d":
  206. ext = ".bmp"
  207. case xStr[:4] == "ffd8":
  208. ext = ".jpg"
  209. case xStr[:2] == "0a":
  210. ext = ".pcx"
  211. default:
  212. ext = ""
  213. }
  214. return ext, nil
  215. }
  216. func SaveImage(path string, img image.Image) (err error) {
  217. imgfile, err := os.Create(path)
  218. defer imgfile.Close()
  219. err = png.Encode(imgfile, img)
  220. return err
  221. }
  222. func SaveBase64ToFile(content, path string) error {
  223. data, err := base64.StdEncoding.DecodeString(content)
  224. if err != nil {
  225. return err
  226. }
  227. f, err := os.Create(path)
  228. defer f.Close()
  229. if err != nil {
  230. return err
  231. }
  232. f.Write(data)
  233. return nil
  234. }
  235. func SaveBase64ToFileBySeek(content, path string) (err error) {
  236. data, err := base64.StdEncoding.DecodeString(content)
  237. exist, err := PathExists(path)
  238. if err != nil {
  239. return
  240. }
  241. if !exist {
  242. f, err := os.Create(path)
  243. if err != nil {
  244. return err
  245. }
  246. n, _ := f.Seek(0, 2)
  247. _, err = f.WriteAt([]byte(data), n)
  248. defer f.Close()
  249. } else {
  250. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  251. if err != nil {
  252. return err
  253. }
  254. n, _ := f.Seek(0, 2)
  255. _, err = f.WriteAt([]byte(data), n)
  256. defer f.Close()
  257. }
  258. return nil
  259. }
  260. func PathExists(path string) (bool, error) {
  261. _, err := os.Stat(path)
  262. if err == nil {
  263. return true, nil
  264. }
  265. if os.IsNotExist(err) {
  266. return false, nil
  267. }
  268. return false, err
  269. }
  270. func StartIndex(page, pagesize int) int {
  271. if page > 1 {
  272. return (page - 1) * pagesize
  273. }
  274. return 0
  275. }
  276. func PageCount(count, pagesize int) int {
  277. if count%pagesize > 0 {
  278. return count/pagesize + 1
  279. } else {
  280. return count / pagesize
  281. }
  282. }
  283. func TrimHtml(src string) string {
  284. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  285. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  286. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  287. src = re.ReplaceAllString(src, "[图片]")
  288. re, _ = regexp.Compile("class[\\S\\s]+?>")
  289. src = re.ReplaceAllString(src, "")
  290. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  291. src = re.ReplaceAllString(src, "")
  292. return strings.TrimSpace(src)
  293. }
  294. func TimeToTimestamp() {
  295. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  296. }
  297. func ToUnicode(text string) string {
  298. textQuoted := strconv.QuoteToASCII(text)
  299. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  300. return textUnquoted
  301. }
  302. func VersionToInt(version string) int {
  303. version = strings.Replace(version, ".", "", -1)
  304. n, _ := strconv.Atoi(version)
  305. return n
  306. }
  307. func IsCheckInList(list []int, s int) bool {
  308. for _, v := range list {
  309. if v == s {
  310. return true
  311. }
  312. }
  313. return false
  314. }
  315. func round(num float64) int {
  316. return int(num + math.Copysign(0.5, num))
  317. }
  318. func toFixed(num float64, precision int) float64 {
  319. output := math.Pow(10, float64(precision))
  320. return float64(round(num*output)) / output
  321. }
  322. func GetWilsonScore(p, n float64) float64 {
  323. if p == 0 && n == 0 {
  324. return 0
  325. }
  326. 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)
  327. }
  328. func ChangeWordsToNum(str string) (numStr string) {
  329. words := ([]rune)(str)
  330. num := 0
  331. n := 0
  332. for i := 0; i < len(words); i++ {
  333. word := string(words[i : i+1])
  334. switch word {
  335. case "万":
  336. if n == 0 {
  337. n = 1
  338. }
  339. n = n * 10000
  340. num = num*10000 + n
  341. n = 0
  342. case "千":
  343. if n == 0 {
  344. n = 1
  345. }
  346. n = n * 1000
  347. num += n
  348. n = 0
  349. case "百":
  350. if n == 0 {
  351. n = 1
  352. }
  353. n = n * 100
  354. num += n
  355. n = 0
  356. case "十":
  357. if n == 0 {
  358. n = 1
  359. }
  360. n = n * 10
  361. num += n
  362. n = 0
  363. case "一":
  364. n += 1
  365. case "二":
  366. n += 2
  367. case "三":
  368. n += 3
  369. case "四":
  370. n += 4
  371. case "五":
  372. n += 5
  373. case "六":
  374. n += 6
  375. case "七":
  376. n += 7
  377. case "八":
  378. n += 8
  379. case "九":
  380. n += 9
  381. case "零":
  382. default:
  383. if n > 0 {
  384. num += n
  385. n = 0
  386. }
  387. if num == 0 {
  388. numStr += word
  389. } else {
  390. numStr += strconv.Itoa(num) + word
  391. num = 0
  392. }
  393. }
  394. }
  395. if n > 0 {
  396. num += n
  397. n = 0
  398. }
  399. if num != 0 {
  400. numStr += strconv.Itoa(num)
  401. }
  402. return
  403. }
  404. func Sha1(data string) string {
  405. sha1 := sha1.New()
  406. sha1.Write([]byte(data))
  407. return hex.EncodeToString(sha1.Sum([]byte("")))
  408. }
  409. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  410. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  411. out, err := exec.Command("bash", "-c", cmd).Output()
  412. if err != nil {
  413. return
  414. }
  415. outTimes := string(out)
  416. fmt.Println("outTimes:", outTimes)
  417. if outTimes != "" {
  418. timeArr := strings.Split(outTimes, ":")
  419. h := timeArr[0]
  420. m := timeArr[1]
  421. s := timeArr[2]
  422. hInt, err := strconv.Atoi(h)
  423. if err != nil {
  424. return playSeconds, err
  425. }
  426. mInt, err := strconv.Atoi(m)
  427. if err != nil {
  428. return playSeconds, err
  429. }
  430. s = strings.Trim(s, " ")
  431. s = strings.Trim(s, "\n")
  432. sInt, err := strconv.ParseFloat(s, 64)
  433. if err != nil {
  434. return playSeconds, err
  435. }
  436. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  437. }
  438. return
  439. }
  440. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  441. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  442. tradeCode = strings.Trim(tradeCode, " ")
  443. tradeCodeInt, err := strconv.Atoi(tradeCode)
  444. if err != nil {
  445. return
  446. }
  447. tradeCodeInt = tradeCodeInt + 1
  448. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  449. return
  450. }
  451. func ConvertToFormatDay(excelDaysString string) string {
  452. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  453. curDiffDay := excelDaysString
  454. b, _ := strconv.Atoi(curDiffDay)
  455. realDiffDay := b - baseDiffDay
  456. realDiffSecond := realDiffDay * 24 * 3600
  457. baseOriginSecond := 1136185445
  458. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  459. return resultTime
  460. }
  461. func GetLocalIP() (ip string, err error) {
  462. addrs, err := net.InterfaceAddrs()
  463. if err != nil {
  464. return
  465. }
  466. for _, addr := range addrs {
  467. ipAddr, ok := addr.(*net.IPNet)
  468. if !ok {
  469. continue
  470. }
  471. if ipAddr.IP.IsLoopback() {
  472. continue
  473. }
  474. if !ipAddr.IP.IsGlobalUnicast() {
  475. continue
  476. }
  477. return ipAddr.IP.String(), nil
  478. }
  479. return
  480. }
  481. func TimeTransferString(format string, t time.Time) string {
  482. str := t.Format(format)
  483. if t.IsZero() {
  484. return ""
  485. }
  486. return str
  487. }