You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.5 KiB
70 lines
1.5 KiB
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"math/rand"
|
|
pb "verifyCode/api/verifyCode"
|
|
)
|
|
|
|
type VerifyCodeService struct {
|
|
pb.UnimplementedVerifyCodeServer
|
|
}
|
|
|
|
func NewVerifyCodeService() *VerifyCodeService {
|
|
return &VerifyCodeService{}
|
|
}
|
|
|
|
func (s *VerifyCodeService) GetVerifyCode(ctx context.Context, req *pb.GetVerifyCodeRequest) (*pb.GetVerifyCodeReply, error) {
|
|
return &pb.GetVerifyCodeReply{
|
|
Code: RandCode(int(req.Length), req.Type),
|
|
}, nil
|
|
}
|
|
|
|
func RandCode(l int, t pb.TYPE) string {
|
|
switch t {
|
|
case pb.TYPE_DEFAULT:
|
|
fallthrough
|
|
case pb.TYPE_DIGIT:
|
|
return randCode("0123456789", l, 4)
|
|
case pb.TYPE_LETTER:
|
|
return randCode("abcdefghijklmnopqrstuvwxyz", l, 5)
|
|
case pb.TYPE_MIXED:
|
|
return randCode("0123456789abcdefghijklmnopqrstuvwxyz", l, 6)
|
|
default:
|
|
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func randCode(chars string, l int, idxBits int) string {
|
|
idxMask := 1<<idxBits - 1
|
|
idxMax := 63 / idxBits
|
|
result := make([]byte, l)
|
|
for i, cache, remain := 0, rand.Int63(), idxMax; i < l; {
|
|
fmt.Println("for:rand.Int63")
|
|
if 0 == remain {
|
|
fmt.Println("if:rand.Int63")
|
|
cache, remain = rand.Int63(), idxMax
|
|
}
|
|
if randIndex := int(cache & int64(idxMask)); randIndex < len(chars) {
|
|
result[i] = chars[randIndex]
|
|
i++
|
|
}
|
|
cache >>= idxBits
|
|
remain--
|
|
}
|
|
|
|
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)
|
|
//}
|