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, r pb.TYPE) string { switch r { case pb.TYPE_DEFAULT: fallthrough case pb.TYPE_DIGIT: return randcode("0123456789", l) case pb.TYPE_LETTRE: return randcode("abcdefghigklmnopqrstuvwxyz", l) case pb.TYPE_MIXED: return randcode("0123456789abcdefghigklmnopqrstuvwxyz", l) default: } return "" } // 随机的核心方法 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) }