2
0

string.go 492 B

123456789101112131415161718192021222324252627
  1. package random
  2. import (
  3. "crypto/rand"
  4. "math/big"
  5. )
  6. const randCharset string = "abcdefghijklmnopqrstuvwxyz1234567890"
  7. func StringWithCharset(length int, charset string) (string, error) {
  8. letters := charset
  9. if charset == "" {
  10. letters = randCharset
  11. }
  12. ret := make([]byte, length)
  13. for i := 0; i < length; i++ {
  14. num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  15. if err != nil {
  16. return "", err
  17. }
  18. ret[i] = letters[num.Int64()]
  19. }
  20. return string(ret), nil
  21. }