utils.go 906 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/rand"
  5. "fmt"
  6. "math/big"
  7. "net/url"
  8. "regexp"
  9. "strconv"
  10. )
  11. // VerifyPhone 验证手机号是否正确
  12. func VerifyPhone(phone string) bool {
  13. // 示例:中国大陆手机号(1开头,11位)
  14. reg := regexp.MustCompile(`^1[3-9]\d{9}$`)
  15. return reg.MatchString(phone)
  16. }
  17. // GetFourRandomDigits 获取4位随机数字
  18. func GetFourRandomDigits() string {
  19. // 生成 [0, 8999] 的安全随机数
  20. n, err := rand.Int(rand.Reader, big.NewInt(9000))
  21. if err != nil {
  22. return ""
  23. }
  24. // 转换为 1000~9999 范围
  25. randomNum := n.Int64() + 1000
  26. return strconv.FormatInt(randomNum, 10)
  27. }
  28. // Md5Sign 使用MD5加密
  29. func Md5Sign(str string) string {
  30. data := []byte(str) //切片
  31. has := md5.Sum(data)
  32. md5str := fmt.Sprintf("%x", has) //将[]byte转成16进制
  33. return md5str
  34. }
  35. // UrlEncode
  36. func UrlEncode(str string) string {
  37. return url.QueryEscape(str)
  38. }