random.go 740 B

123456789101112131415161718192021222324252627282930313233
  1. package stringutil
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "strconv"
  6. "time"
  7. )
  8. func init() {
  9. rand.Seed(time.Now().UnixNano())
  10. }
  11. const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  12. // UniqueID returns randomly generated string with prefix
  13. func UniqueID(prefix string, l uint) string {
  14. return fmt.Sprintf("%s%s", prefix, RandomString(l))
  15. }
  16. func UniqueIDBaseTime(prefix string) string {
  17. timeStr := strconv.FormatUint(uint64(time.Now().UnixNano()), 36)
  18. return fmt.Sprintf("%s%s%s", prefix, timeStr, RandomString(2))
  19. }
  20. // RandomString returns randomly generated string
  21. func RandomString(l uint) string {
  22. s := make([]byte, l)
  23. for i := 0; i < int(l); i++ {
  24. s[i] = chars[rand.Intn(len(chars))]
  25. }
  26. return string(s)
  27. }