random.go 771 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package util
  2. import (
  3. "math/rand"
  4. "time"
  5. )
  6. var defaultLetters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  7. // RandomString returns a random string with a fixed length
  8. func RandomString(n int, allowedChars ...[]rune) string {
  9. var letters []rune
  10. if len(allowedChars) == 0 {
  11. letters = defaultLetters
  12. } else {
  13. letters = allowedChars[0]
  14. }
  15. b := make([]rune, n)
  16. for i := range b {
  17. b[i] = letters[rand.Intn(len(letters))]
  18. }
  19. return string(b)
  20. }
  21. func RandInt64(min, max int64) int64 {
  22. s := rand.NewSource(time.Now().UnixNano())
  23. r := rand.New(s)
  24. return min + r.Int63n(max-min+1)
  25. }
  26. func RandFloat64(min, max float64) float64 {
  27. s := rand.NewSource(time.Now().UnixNano())
  28. r := rand.New(s)
  29. return min + r.Float64()*(max-min)
  30. }