Simplify id generation
This commit is contained in:
parent
c5f12920b0
commit
fcb88c8a85
16
util/rand.go
16
util/rand.go
|
@ -2,24 +2,18 @@ package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"math/big"
|
"encoding/base64"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var enc = base64.URLEncoding
|
||||||
runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
|
|
||||||
runes_length = len(runes)
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewRandID(n int) (string, error) {
|
func NewRandID(n int) (string, error) {
|
||||||
data := make([]rune, n)
|
data := make([]byte, enc.DecodedLen(n))
|
||||||
for i := range data {
|
_, err := rand.Read(data)
|
||||||
num, err := rand.Int(rand.Reader, big.NewInt(int64(runes_length)))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
data[i] = runes[num.Int64()]
|
return enc.EncodeToString(data), nil
|
||||||
}
|
|
||||||
return string(data), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSessionID() (string, error) {
|
func NewSessionID() (string, error) {
|
||||||
|
|
Loading…
Reference in New Issue