-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomstring.go
90 lines (77 loc) · 2.44 KB
/
randomstring.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package randomstring
import (
"crypto/rand"
"errors"
"math/big"
"strings"
)
type Charset string
const (
Alphanumeric = Charset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
Lowercase = Charset("abcdefghijklmnopqrstuvwxyz")
Uppercase = Charset("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Numeric = Charset("0123456789")
SpecialCharacters = Charset("!@#$%^&*()-_=+[]{}|;:'<>,.?/~")
)
var (
GenerateString = generateString
)
type GenerationOptions struct {
Length int
DisableNumeric bool
DisableLowercase bool
DisableUppercase bool
EnableSpecialCharacter bool
CustomCharset Charset
}
// generateStringFromCharset generates a random string from a given charset
func generateStringFromCharset(charset Charset, length int) (string, error) {
if len(charset) == 0 || length <= 0 {
return "", errors.New("invalid charset or length")
}
result := make([]byte, length)
charsetLen := big.NewInt(int64(len(charset)))
for i := 0; i < length; i++ {
randomIndex, err := rand.Int(rand.Reader, charsetLen)
if err != nil {
return "", err
}
result[i] = charset[randomIndex.Int64()]
}
return string(result), nil
}
// modifyCharset modifies the charset based on the options
func modifyCharset(opts GenerationOptions, charsetMappings map[string]Charset, charset Charset) Charset {
if opts.DisableNumeric {
charset = Charset(strings.ReplaceAll(string(charset), string(charsetMappings["numeric"]), ""))
}
if opts.DisableLowercase {
charset = Charset(strings.ReplaceAll(string(charset), string(charsetMappings["lowercase"]), ""))
}
if opts.DisableUppercase {
charset = Charset(strings.ReplaceAll(string(charset), string(charsetMappings["uppercase"]), ""))
}
if opts.EnableSpecialCharacter {
charset += charsetMappings["specialCharater"]
}
return charset
}
// generateString generates a random string based on the options
func generateString(opts GenerationOptions) (string, error) {
charsetMappings := map[string]Charset{
"numeric": Numeric,
"lowercase": Lowercase,
"uppercase": Uppercase,
"specialCharater": SpecialCharacters,
}
charset := Alphanumeric
if opts.CustomCharset != "" {
charset = opts.CustomCharset
} else {
charset = modifyCharset(opts, charsetMappings, charset)
}
if len(charset) == 0 {
return "", errors.New("resulting charset is empty. adjust your options")
}
return generateStringFromCharset(charset, opts.Length)
}