utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "io/ioutil"
  7. "math/rand"
  8. "os"
  9. "strings"
  10. "time"
  11. "github.com/google/uuid"
  12. )
  13. func Hmac(data string) string {
  14. h := md5.New()
  15. h.Write([]byte(data))
  16. return hex.EncodeToString(h.Sum(nil))
  17. }
  18. func IsStringEmpty(str string) bool {
  19. return strings.Trim(str, " ") == ""
  20. }
  21. func GetUUID() string {
  22. u := uuid.New()
  23. return strings.ReplaceAll(u.String(), "-", "")
  24. }
  25. func PathExists(path string) bool {
  26. _, err := os.Stat(path)
  27. if err == nil {
  28. return true
  29. }
  30. if os.IsNotExist(err) {
  31. return false
  32. }
  33. return false
  34. }
  35. func Base64ToImage(imageBase64 string) ([]byte, error) {
  36. image, err := base64.StdEncoding.DecodeString(imageBase64)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return image, nil
  41. }
  42. func GetDirFiles(dir string) ([]string, error) {
  43. dirList, err := ioutil.ReadDir(dir)
  44. if err != nil {
  45. return nil, err
  46. }
  47. filesRet := make([]string, 0)
  48. for _, file := range dirList {
  49. if file.IsDir() {
  50. files, err := GetDirFiles(dir + string(os.PathSeparator) + file.Name())
  51. if err != nil {
  52. return nil, err
  53. }
  54. filesRet = append(filesRet, files...)
  55. } else {
  56. filesRet = append(filesRet, dir+string(os.PathSeparator)+file.Name())
  57. }
  58. }
  59. return filesRet, nil
  60. }
  61. func GetCurrentTimeStamp() int64 {
  62. return time.Now().UnixNano() / 1e6
  63. }
  64. // slice去重
  65. func RemoveRepByMap(slc []string) []string {
  66. result := []string{}
  67. tempMap := map[string]byte{}
  68. for _, e := range slc {
  69. l := len(tempMap)
  70. tempMap[e] = 0
  71. if len(tempMap) != l {
  72. result = append(result, e)
  73. }
  74. }
  75. return result
  76. }
  77. // #取得随机字符串:通过打乱slice来操作
  78. func GetRandString(length int, char string, rand_x int64) string {
  79. if length < 1 {
  80. return ""
  81. }
  82. if len(char) <= 6 || len(char) <= length {
  83. char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  84. }
  85. charArr := strings.Split(char, "")
  86. ran := rand.New(rand.NewSource(time.Now().UnixMilli() + rand_x))
  87. l := len(charArr)
  88. for i := l - 1; i > 0; i-- {
  89. r := ran.Intn(i)
  90. charArr[r], charArr[i] = charArr[i], charArr[r]
  91. }
  92. rchar := charArr[:length]
  93. return strings.Join(rchar, "")
  94. }