-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generators.go
47 lines (42 loc) · 848 Bytes
/
generators.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package gosl
import (
"crypto/rand"
"encoding/hex"
"errors"
)
// RandomString generates a random string with a given size using built-in
// "crypto/rand" and "encoding/hex" packages.
//
// If err != nil returns zero-value for a string and error.
//
// Example:
//
// package main
//
// import (
// "fmt"
// "log"
//
// "github.com/koddr/gosl"
// )
//
// func main() {
// s, err := gosl.RandomString(8)
// if err != nil {
// log.Fatal(err)
// }
//
// fmt.Println(s)
// }
func RandomString(size int) (string, error) {
if size <= 0 {
return "", errors.New("can't generate random string with zero or negative size")
}
bufferSize := size
if size%2 == 0 && size >= 4 {
bufferSize = size / 2 // hack to reduce buffer size and B/op
}
b := make([]byte, bufferSize)
_, _ = rand.Read(b)
return hex.EncodeToString(b)[:size], nil
}