2020-01-06 14:32:15 +01:00
|
|
|
package rnd
|
2019-11-08 06:53:40 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
2019-12-27 05:18:52 +01:00
|
|
|
"encoding/binary"
|
2020-01-12 14:00:56 +01:00
|
|
|
"fmt"
|
2019-12-27 05:18:52 +01:00
|
|
|
"strconv"
|
2019-11-08 06:53:40 +01:00
|
|
|
)
|
|
|
|
|
2022-04-15 09:42:07 +02:00
|
|
|
// GenerateToken returns a random token with length of up to 10 characters.
|
|
|
|
func GenerateToken(size uint) string {
|
2019-12-27 05:18:52 +01:00
|
|
|
if size > 10 || size < 1 {
|
2020-01-12 14:00:56 +01:00
|
|
|
panic(fmt.Sprintf("size out of range: %d", size))
|
2019-12-27 05:18:52 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
result := make([]byte, 0, 14)
|
|
|
|
b := make([]byte, 8)
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2019-12-04 15:14:04 +01:00
|
|
|
if _, err := rand.Read(b); err != nil {
|
2020-01-12 14:00:56 +01:00
|
|
|
panic(err)
|
2019-12-04 15:14:04 +01:00
|
|
|
}
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2019-12-27 05:18:52 +01:00
|
|
|
randomInt := binary.BigEndian.Uint64(b)
|
|
|
|
|
|
|
|
result = append(result, strconv.FormatUint(randomInt, 36)...)
|
|
|
|
|
|
|
|
for i := len(result); i < cap(result); i++ {
|
|
|
|
result = append(result, byte(123-(cap(result)-i)))
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(result[:size])
|
|
|
|
}
|