tool.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. rand.Seed(time.Now().UnixNano())
  71. <-time.After(time.Nanosecond)
  72. return rand.Intn(max)
  73. }
  74. func FindIPv4(input string) string {
  75. partIp := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
  76. must := partIp + "\\." + partIp + "\\." + partIp + "\\." + partIp
  77. matchMe := regexp.MustCompile(must)
  78. return matchMe.FindString(input)
  79. }
  80. func RandString(n int) string {
  81. var letterRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  82. b := make([]rune, n)
  83. for i := range b {
  84. b[i] = letterRunes[RandInt(len(letterRunes))]
  85. }
  86. return string(b)
  87. }