-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgostrgen.go
61 lines (54 loc) · 1.09 KB
/
gostrgen.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
// gostrgen
package gostrgen
import (
"errors"
"math/rand"
"strings"
"time"
)
const None = 0
const Lower = 1 << 0
const Upper = 1 << 1
const Digit = 1 << 2
const Punct = 1 << 3
const LowerUpper = Lower | Upper
const LowerDigit = Lower | Digit
const UpperDigit = Upper | Digit
const LowerUpperDigit = LowerUpper | Digit
const All = LowerUpperDigit | Punct
const lower = "abcdefghijklmnopqrstuvwxyz"
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const digit = "0123456789"
const punct = "~!@#$%^&*()_+-="
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func RandGen(size int, set int, include string, exclude string) (string, error) {
all := include
if set&Lower > 0 {
all += lower
}
if set&Upper > 0 {
all += upper
}
if set&Digit > 0 {
all += digit
}
if set&Punct > 0 {
all += punct
}
lenAll := len(all)
if len(exclude) >= lenAll {
return "", errors.New("Too much to exclude.")
}
buf := make([]byte, size)
for i := 0; i < size; i++ {
b := all[rand.Intn(lenAll)]
if strings.Contains(exclude, string(b)) {
i--
continue
}
buf[i] = b
}
return string(buf), nil
}