tool.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package assist
  2. import (
  3. "fmt"
  4. "git.bvbej.com/bvbej/base-golang/pkg/time_parse"
  5. "math"
  6. "math/rand"
  7. "regexp"
  8. "strconv"
  9. "time"
  10. "unicode"
  11. )
  12. func GetOrderNumber() string {
  13. parse, _ := time.Parse(time_parse.CSTLayout, "2021-04-27 00:00:00")
  14. hours := time.Now().Sub(parse).Hours()
  15. day := math.Floor(hours / 24)
  16. prefix := fmt.Sprintf("%05d", int64(day))
  17. format := time.Now().Format("") + "%0" + strconv.Itoa(10) + "d"
  18. n := math.Pow10(10)
  19. return prefix + fmt.Sprintf(format, rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(int64(n)))
  20. }
  21. func ByteFmt(size int64) string {
  22. var unitArr = []string{"B", "KB", "MB", "GB", "TB", "EB"}
  23. if size == 0 {
  24. return "unknown"
  25. }
  26. fs := float64(size)
  27. p := int(math.Log(fs) / math.Log(1024))
  28. val := fs / math.Pow(1024, float64(p))
  29. _, frac := math.Modf(val)
  30. if frac > 0 {
  31. return fmt.Sprintf("%.1f%s", math.Floor(val*10)/10, unitArr[p])
  32. } else {
  33. return fmt.Sprintf("%d%s", int(val), unitArr[p])
  34. }
  35. }
  36. func UniqueArray[T comparable](array []T) []T {
  37. result := make([]T, 0, len(array))
  38. temp := map[T]struct{}{}
  39. for _, item := range array {
  40. if _, ok := temp[item]; !ok {
  41. temp[item] = struct{}{}
  42. result = append(result, item)
  43. }
  44. }
  45. return result
  46. }
  47. func InArray[T comparable](item T, array []T) bool {
  48. for _, s := range array {
  49. if item == s {
  50. return true
  51. }
  52. }
  53. return false
  54. }
  55. func CurrencyDecimal(value float64) float64 {
  56. value, _ = strconv.ParseFloat(fmt.Sprintf("%.8f", value), 64)
  57. return value
  58. }
  59. func IsChinese(str string) bool {
  60. var count int
  61. for _, v := range str {
  62. if unicode.Is(unicode.Han, v) {
  63. count++
  64. break
  65. }
  66. }
  67. return count > 0
  68. }
  69. func RandInt(max int) int {
  70. if max <= 0 {
  71. return 0
  72. }
  73. rand.Seed(time.Now().UnixNano())
  74. <-time.After(time.Nanosecond)
  75. return rand.Intn(max)
  76. }
  77. func FindIPv4(input string) string {
  78. partIp := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
  79. must := partIp + "\\." + partIp + "\\." + partIp + "\\." + partIp
  80. matchMe := regexp.MustCompile(must)
  81. return matchMe.FindString(input)
  82. }
  83. func RandString(n int) string {
  84. var letterRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  85. b := make([]rune, n)
  86. for i := range b {
  87. b[i] = letterRunes[RandInt(len(letterRunes))]
  88. }
  89. return string(b)
  90. }