utils.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package utils
  4. import (
  5. "fmt"
  6. "math/rand"
  7. "time"
  8. )
  9. const (
  10. NUmStr = "0123456789"
  11. //CharStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  12. CharStr = "abcdefghijklmnopqrstuvwxyz"
  13. SpecStr = "+=-@#~,.[]()!%^*$"
  14. )
  15. func GenerateRandomStr(length int, charset string) string {
  16. time.Sleep(1*time.Microsecond)
  17. rand.Seed(time.Now().UnixNano())
  18. //初始化密码切片
  19. var passwd []byte = make([]byte, length, length)
  20. //源字符串
  21. var sourceStr string
  22. //判断字符类型,如果是数字
  23. if charset == "num" {
  24. sourceStr = NUmStr
  25. //如果选的是字符
  26. } else if charset == "char" {
  27. sourceStr = charset
  28. //如果选的是混合模式
  29. } else if charset == "mix" {
  30. sourceStr = fmt.Sprintf("%s%s", NUmStr, CharStr)
  31. //如果选的是高级模式
  32. } else if charset == "advance" {
  33. sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
  34. } else {
  35. sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
  36. }
  37. //遍历,生成一个随机index索引,
  38. for i := 0; i < length; i++ {
  39. index := rand.Intn(len(sourceStr))
  40. passwd[i] = sourceStr[index]
  41. }
  42. return string(passwd)
  43. }