aboutsummaryrefslogtreecommitdiff
path: root/internal/strutil/strutil.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/strutil/strutil.go')
-rw-r--r--internal/strutil/strutil.go29
1 files changed, 29 insertions, 0 deletions
diff --git a/internal/strutil/strutil.go b/internal/strutil/strutil.go
index a2b84a20..b1de241f 100644
--- a/internal/strutil/strutil.go
+++ b/internal/strutil/strutil.go
@@ -5,6 +5,8 @@
package strutil
import (
+ "crypto/rand"
+ "math/big"
"unicode"
)
@@ -15,3 +17,30 @@ func ToUpperFirst(s string) string {
}
return ""
}
+
+// RandomChars returns a generated string in given number of random characters.
+func RandomChars(n int) (string, error) {
+ const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+
+ randomInt := func(max *big.Int) (int, error) {
+ r, err := rand.Int(rand.Reader, max)
+ if err != nil {
+ return 0, err
+ }
+
+ return int(r.Int64()), nil
+ }
+
+ buffer := make([]byte, n)
+ max := big.NewInt(int64(len(alphanum)))
+ for i := 0; i < n; i++ {
+ index, err := randomInt(max)
+ if err != nil {
+ return "", err
+ }
+
+ buffer[i] = alphanum[index]
+ }
+
+ return string(buffer), nil
+}