RandomChars returns a generated string in given number of random characters.
(n int)
| 16 | |
| 17 | // RandomChars returns a generated string in given number of random characters. |
| 18 | func RandomChars(n int) (string, error) { |
| 19 | const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 20 | |
| 21 | randomInt := func(max *big.Int) (int, error) { |
| 22 | r, err := rand.Int(rand.Reader, max) |
| 23 | if err != nil { |
| 24 | return 0, err |
| 25 | } |
| 26 | |
| 27 | return int(r.Int64()), nil |
| 28 | } |
| 29 | |
| 30 | buffer := make([]byte, n) |
| 31 | max := big.NewInt(int64(len(alphanum))) |
| 32 | for i := 0; i < n; i++ { |
| 33 | index, err := randomInt(max) |
| 34 | if err != nil { |
| 35 | return "", err |
| 36 | } |
| 37 | |
| 38 | buffer[i] = alphanum[index] |
| 39 | } |
| 40 | |
| 41 | return string(buffer), nil |
| 42 | } |
| 43 | |
| 44 | // Ellipsis returns a truncated string and appends "..." to the end of the |
| 45 | // string if the string length is larger than the threshold. Otherwise, the |