1234567891011121314151617181920212223242526272829303132333435363738 |
- package util
- import (
- "math/rand"
- "time"
- )
- const (
- letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
- )
- func init() {
- rand.Seed(time.Now().UnixNano())
- }
- // https://github.com/kpbird/golang_random_string
- func RandString(n int) string {
- output := make([]byte, n)
- // We will take n bytes, one byte for each character of output.
- randomness := make([]byte, n)
- // read all random
- _, err := rand.Read(randomness)
- if err != nil {
- panic(err)
- }
- l := len(letterBytes)
- // fill output
- for pos := range output {
- // get random item
- random := randomness[pos]
- // random % 64
- randomPos := random % uint8(l)
- // put into output
- output[pos] = letterBytes[randomPos]
- }
- return string(output)
- }
|