/
random.go
65 lines (55 loc) · 1.67 KB
/
random.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package utils
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"math/rand"
"time"
)
func RandomNumber(min, max int) string {
rand.Seed(time.Now().UnixNano())
code := rand.Intn(max-min+1) + min
return fmt.Sprintf("%d", code)
}
// Bytes generates n random bytes
func Bytes(n int) []byte {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
return b
}
// Base64 generates a random base64 string with length of n
func Base64(n int) string {
return String(n, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/")
}
// Base64 generates a random base62 string with length of n
func Base62(s int) string {
return String(s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
}
// Hex generates a random hex string with length of n
// e.g: 67aab2d956bd7cc621af22cfb169cba8
func Hex(n int) string { return hex.EncodeToString(Bytes(n)) }
// list of default letters that can be used to make a random string when calling String
// function with no letters provided
var defLetters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// String generates a random string using only letters provided in the letters parameter
// if user ommit letters parameters, this function will use defLetters instead
func String(n int, letters ...string) string {
var letterRunes []rune
if len(letters) == 0 {
letterRunes = defLetters
} else {
letterRunes = []rune(letters[0])
}
var bb bytes.Buffer
bb.Grow(n)
l := uint32(len(letterRunes))
// on each loop, generate one random rune and append to output
for i := 0; i < n; i++ {
bb.WriteRune(letterRunes[binary.BigEndian.Uint32(Bytes(4))%l])
}
return bb.String()
}