util.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package common
  2. import (
  3. "crypto/rand"
  4. "math/big"
  5. "net/mail"
  6. "strings"
  7. "github.com/google/uuid"
  8. )
  9. // HasPrefixes returns true if the string s has any of the given prefixes.
  10. func HasPrefixes(src string, prefixes ...string) bool {
  11. for _, prefix := range prefixes {
  12. if strings.HasPrefix(src, prefix) {
  13. return true
  14. }
  15. }
  16. return false
  17. }
  18. // ValidateEmail validates the email.
  19. func ValidateEmail(email string) bool {
  20. if _, err := mail.ParseAddress(email); err != nil {
  21. return false
  22. }
  23. return true
  24. }
  25. func GenUUID() string {
  26. return uuid.New().String()
  27. }
  28. func Min(x, y int) int {
  29. if x < y {
  30. return x
  31. }
  32. return y
  33. }
  34. var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  35. // RandomString returns a random string with length n.
  36. func RandomString(n int) (string, error) {
  37. var sb strings.Builder
  38. sb.Grow(n)
  39. for i := 0; i < n; i++ {
  40. // The reason for using crypto/rand instead of math/rand is that
  41. // the former relies on hardware to generate random numbers and
  42. // thus has a stronger source of random numbers.
  43. randNum, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  44. if err != nil {
  45. return "", err
  46. }
  47. if _, err := sb.WriteRune(letters[randNum.Uint64()]); err != nil {
  48. return "", err
  49. }
  50. }
  51. return sb.String(), nil
  52. }