rand.go 734 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package util
  2. import (
  3. "math/rand"
  4. "time"
  5. )
  6. const (
  7. letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  8. )
  9. func init() {
  10. rand.Seed(time.Now().UnixNano())
  11. }
  12. // https://github.com/kpbird/golang_random_string
  13. func RandString(n int) string {
  14. output := make([]byte, n)
  15. // We will take n bytes, one byte for each character of output.
  16. randomness := make([]byte, n)
  17. // read all random
  18. _, err := rand.Read(randomness)
  19. if err != nil {
  20. panic(err)
  21. }
  22. l := len(letterBytes)
  23. // fill output
  24. for pos := range output {
  25. // get random item
  26. random := randomness[pos]
  27. // random % 64
  28. randomPos := random % uint8(l)
  29. // put into output
  30. output[pos] = letterBytes[randomPos]
  31. }
  32. return string(output)
  33. }