utils.go 842 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "math/big"
  5. "regexp"
  6. "strconv"
  7. "sync"
  8. )
  9. // Utils 工具单例
  10. type Utils struct{}
  11. var (
  12. instance *Utils
  13. once sync.Once
  14. )
  15. // GetUtils 获取单例实例
  16. func GetUtils() *Utils {
  17. once.Do(func() {
  18. instance = &Utils{}
  19. })
  20. return instance
  21. }
  22. // VerifyPhone 验证手机号是否正确
  23. func (u *Utils) VerifyPhone(phone string) bool {
  24. // 示例:中国大陆手机号(1开头,11位)
  25. reg := regexp.MustCompile(`^1[3-9]\d{9}$`)
  26. return reg.MatchString(phone)
  27. }
  28. // GetFourRandomDigits 获取4位随机数字
  29. func (u *Utils) GetFourRandomDigits() string {
  30. // 生成 [0, 8999] 的安全随机数
  31. n, err := rand.Int(rand.Reader, big.NewInt(9000))
  32. if err != nil {
  33. return ""
  34. }
  35. // 转换为 1000~9999 范围
  36. randomNum := n.Int64() + 1000
  37. return strconv.FormatInt(randomNum, 10)
  38. }