-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
52 lines (44 loc) · 1.05 KB
/
token.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
package str
import (
"math/rand"
"time"
)
type TokenOptions struct {
Length uint
Charset string
Prefix string
}
var defaultTokenOptions *TokenOptions
func init() {
defaultTokenOptions = &TokenOptions{
Length: 20,
Charset: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789",
}
rand.Seed(time.Now().UnixNano())
}
// SetTokenOptions - set the options for token generation
func SetTokenOptions(options *TokenOptions) {
defaultTokenOptions = options
}
// Token - create pseudorandom token
func Token() string {
return TokenWithOptions(defaultTokenOptions)
}
// TokenWithOptions - create pseudorandom token with user-supplied options
func TokenWithOptions(options *TokenOptions) string {
cl := len(options.Charset)
pl := len(options.Prefix)
if options.Length < 1 || cl == 0 {
return ""
}
if pl >= int(options.Length) {
return options.Prefix
}
rounds := int(options.Length) - pl
var token string
for i := 0; i < rounds; i++ {
guard := rand.Intn(cl)
token += options.Charset[guard : guard+1]
}
return options.Prefix + token
}