蛋蛋星球 后台端

2 settimane fa
123456789101112131415161718192021222324252627282930313233343536373839
  1. package utils
  2. import (
  3. "math/rand"
  4. "sync"
  5. "time"
  6. )
  7. const (
  8. letterBytes = "0123456789"
  9. )
  10. var mu sync.Mutex
  11. var generatedCodes = make(map[string]struct{})
  12. func init() {
  13. rand.Seed(time.Now().UnixNano())
  14. }
  15. func randomString(lens int) string {
  16. b := make([]byte, lens)
  17. for i := range b {
  18. b[i] = letterBytes[rand.Intn(len(letterBytes))]
  19. }
  20. return string(b)
  21. }
  22. func GenerateUniqueInvitationCode(lens int) string {
  23. var code string
  24. for {
  25. code = randomString(lens)
  26. mu.Lock()
  27. if _, ok := generatedCodes[code]; !ok {
  28. generatedCodes[code] = struct{}{}
  29. mu.Unlock()
  30. return code
  31. }
  32. mu.Unlock()
  33. }
  34. }