RandomString returns a random string with length n.
(n int)
| 41 | |
| 42 | // RandomString returns a random string with length n. |
| 43 | func RandomString(n int) (string, error) { |
| 44 | var sb strings.Builder |
| 45 | sb.Grow(n) |
| 46 | for i := 0; i < n; i++ { |
| 47 | // The reason for using crypto/rand instead of math/rand is that |
| 48 | // the former relies on hardware to generate random numbers and |
| 49 | // thus has a stronger source of random numbers. |
| 50 | randNum, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters)))) |
| 51 | if err != nil { |
| 52 | return "", err |
| 53 | } |
| 54 | if _, err := sb.WriteRune(letters[randNum.Uint64()]); err != nil { |
| 55 | return "", err |
| 56 | } |
| 57 | } |
| 58 | return sb.String(), nil |
| 59 | } |
| 60 | |
| 61 | // HasPrefixes returns true if the string s has any of the given prefixes. |
| 62 | func HasPrefixes(src string, prefixes ...string) bool { |
no test coverage detected