验证码随机生成的业务逻辑,优化版

main
maomao 3 months ago
parent 12958863b1
commit fd0588acab

@ -2,7 +2,9 @@ package main
import ( import (
"flag" "flag"
"math/rand"
"os" "os"
"time"
"verifyCode/internal/conf" "verifyCode/internal/conf"
@ -79,7 +81,8 @@ func main() {
panic(err) panic(err)
} }
defer cleanup() defer cleanup()
//set rand seed
rand.Seed(time.Now().UnixNano())
// start and wait for stop signal // start and wait for stop signal
if err := app.Run(); err != nil { if err := app.Run(); err != nil {
panic(err) panic(err)

@ -3,7 +3,6 @@ package service
import ( import (
"context" "context"
"math/rand" "math/rand"
pb "verifyCode/api/verifyCode" pb "verifyCode/api/verifyCode"
) )
@ -27,24 +26,56 @@ func RandCode(l int, r pb.TYPE) string {
fallthrough fallthrough
case pb.TYPE_DIGIT: case pb.TYPE_DIGIT:
return randcode("0123456789", l) return randcode("0123456789", l, 4)
case pb.TYPE_LETTRE: case pb.TYPE_LETTRE:
return randcode("abcdefghigklmnopqrstuvwxyz", l) return randcode("abcdefghigklmnopqrstuvwxyz", l, 5)
case pb.TYPE_MIXED: case pb.TYPE_MIXED:
return randcode("0123456789abcdefghigklmnopqrstuvwxyz", l) return randcode("0123456789abcdefghigklmnopqrstuvwxyz", l, 6)
default: default:
}
return "" return ""
}
} }
// 随机的核心方法 // 随机数和新方法:优化实现
func randcode(chars string, l int) string { // 一次随机多次使用,分部分多次使用
charsLen := len(chars) func randcode(chars string, l, idxBits int) string {
//计算有效的二进制数基于char的长度
//推荐写死chars固定idxBits固定
//形成掩码。mask
//例如使用低六位00000000000111111
idxMask := 1<<idxBits - 1 //00001000000 - 1 = 00000111111
//63位可以使用多少次
idxMax := 63 / idxBits
//结果
result := make([]byte, l) result := make([]byte, l)
for i := 0; i < l; i++ { //生成随机数
randIndex := rand.Intn(charsLen) //cache:随机位缓存
//remain:还可以用多少次
for i, cache, remain := 0, rand.Int63(), idxMax; i < l; {
if remain == 0 {
cache, remain = rand.Int63(), idxMax
}
//利用掩码获取有效位的随机数
if randIndex := int(cache & int64(idxMask)); randIndex < len(chars) {
result[i] = chars[randIndex] result[i] = chars[randIndex]
i++
}
//使用下一组随即位
cache >>= idxBits
//减少一次使用次数
remain--
} }
return string(result) return string(result)
} }
// 随机的核心方法:简单实现
//func randcode(chars string, l int) string {
// charsLen := len(chars)
// result := make([]byte, l)
// for i := 0; i < l; i++ {
// randIndex := rand.Intn(charsLen)
// result[i] = chars[randIndex]
// }
// return string(result)
//}

Loading…
Cancel
Save