package service import ( "context" "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, idxBits int) string { //idxBits = len(fmt.Sprintf("%b",len(chars))) idxMask := 1<>= idxBits remain-- } return string(result) } // 简单实现 func simpleRandCode(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) }