package service import ( "context" "customer/api/verifyCode" "customer/internal/data" "github.com/go-kratos/kratos/v2/transport/grpc" "regexp" "time" pb "customer/api/customer" ) type CustomerService struct { pb.UnimplementedCustomerServer cd *data.CustomerData } func NewCustomerService(cd *data.CustomerData) *CustomerService { return &CustomerService{ cd: cd, } } func (s *CustomerService) GetVerifyCode(ctx context.Context, req *pb.GetVerifyCodeReq) (*pb.GetVerifyCodeResp, error) { //1.效验手机号 正则表达式 pattern := `^(13\d|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18\d|19[0-35-9])\d{8}$` regexpPattern := regexp.MustCompile(pattern) if !regexpPattern.MatchString(req.Telephone) { return &pb.GetVerifyCodeResp{ Code: 1, Message: "电话号码格式错误", }, nil } //获取验证码 conn, err := grpc.DialInsecure( context.Background(), grpc.WithEndpoint("localhost:9000"), ) if err != nil { return &pb.GetVerifyCodeResp{ Code: 1, Message: "验证码服务不可用", }, nil } // defer func() { _ = conn.Close() }() client := verifyCode.NewVerifyCodeClient(conn) reply, err := client.GetVerifyCode(context.Background(), &verifyCode.GetVerifyCodeRequest{ Length: 6, Type: 1, }) if err != nil { return &pb.GetVerifyCodeResp{ Code: 1, Message: "验证码获取错误", }, nil } //3.redis的临时存储 const life = 60 if err := s.cd.SetVerifyCode(req.Telephone, reply.Code, life); err != nil { return &pb.GetVerifyCodeResp{ Code: 1, Message: "验证码获取错误(Redis的错误)", }, nil } //响应 return &pb.GetVerifyCodeResp{ Code: 0, VerifyCode: reply.Code, Message: "获取验证码成功", VerifyCodeTime: time.Now().Unix(), VerifyCodeLife: life, }, nil }