feat(verify):完成随机验证码的生成。

This commit is contained in:
徐涛
2023-07-11 10:02:22 +08:00
parent 539e4ec384
commit 4fdf9be6d2
3 changed files with 43 additions and 3 deletions

2
random/random.go Normal file
View File

@@ -0,0 +1,2 @@
// 提供用于生成伪随机数的工具函数。
package random

View File

@@ -0,0 +1,38 @@
// 提供一个快速生成指定长度的随机验证码的工具。
package verifyCode
import (
"math/rand"
"time"
"unsafe"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
var src = rand.NewSource(time.Now().UnixNano())
const (
// 6 bits to represent a letter index
letterIdBits = 6
// All 1-bits as many as letterIdBits
letterIdMask = 1<<letterIdBits - 1
letterIdMax = 63 / letterIdBits
)
// 生成一个指定长度的随机验证码。
func RandStr(n int) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdMax
}
if idx := int(cache & letterIdMask); idx < len(letters) {
b[i] = letters[idx]
i--
}
cache >>= letterIdBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}