gRPC验证器

本文介绍了如何在Go项目中安装并使用protobuf-gen-validate插件进行数据验证,包括编写带有验证规则的protobuf消息,以及在gRPC服务中集成验证拦截器。
摘要由CSDN通过智能技术生成

文档

GitHub - bufbuild/protoc-gen-validate: Protocol Buffer Validation - Being replaced by github.com/bufbuild/protovalidate

安装

安装插件。

go install github.com/envoyproxy/protoc-gen-validate@latest

保存validate.proto文件在这里插入图片描述

编写proto

syntax = "proto3";

package proto;

option go_package = "/test;test";

import "proto/validate.proto";

message RequestInfo {
  uint64 id = 1 [(validate.rules).uint64.gt = 999];

  string email = 2 [(validate.rules).string.email = true];

  string name = 3 [(validate.rules).string = {
    max_bytes: 256,
  }];
}

message ResponseInfo {
  string res = 1;
}

service Test {
  rpc Test (RequestInfo) returns (ResponseInfo) {}
}

生成文件

通过 --validate_out设置 validate生成的路径。

因为 validate.proto文件使用了 google原生的类型,所以需要设置 google原生的 proto文件路径。

protoc -I D:\GoPath\pkg\mod\github.com\protocolbuffers\protobuf@v4.25.2+incompatible\src -I . --go_out=. --go-grpc_out=. --validate_out="lang=go:." ./proto/test.proto

代码中使用

在拦截器中使用 Validate方法进行验证,具体请看下面代码。

服务端

package main

import (
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    "net"
    "strconv"
    "test/test"
)

type Test struct {
    test.UnimplementedTestServer
}

type Validator interface {
    Validate() error
}

func (t *Test) Test(ctx context.Context, req *test.RequestInfo) (*test.ResponseInfo, error) {
    return &test.ResponseInfo{Res: strconv.FormatUint(req.Id, 10)}, nil
}

func main() {

    // 监听
    listen, _ := net.Listen("tcp", ":8080")

    // 设置拦截器
    opt := grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
        if r, ok := req.(Validator); ok {
            // 进行验证
            if err := r.Validate(); err != nil {
                return nil, status.Error(codes.InvalidArgument, err.Error())
            }
        }
        res, err := handler(ctx, req)
        return res, err
    })

    // 实例化grpc服务
    s := grpc.NewServer(opt)

    // 注册服务
    test.RegisterTestServer(s, &Test{})

    // 启动
    s.Serve(listen)
}

客户端

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
    "test/test"
)

func main() {

    // 建立连接
    conn, _ := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))

    // 实例化客户端
    client := test.NewTestClient(conn)

    res, err := client.Test(context.Background(), &test.RequestInfo{
        Id:    999,
        Name:  "Protocol Buffer",
        Email: "1231456@qq.com",
    })
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(res.Res)
    }

}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值