util.go 1.6 KB

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