common.go 10 KB

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