/go-zero-validate

protoc-gen-validate as go-zero's validator

Primary LanguageGo

go-zero-validate

proto验证参数类型

基于go-zero的protoc-gen-validate使用

使用方式

Makefile

# grpc生成xxxx.pb.validate.go文件
make validate

# goctl生成pb已经常规go-zero文件
make gen-rpc

# 综合前两步
make gen-rpc-validate

手动调用参数校验

func (l *CreateLogic) Create(in *user.CreateRequest) (*user.CreateResponse, error) {
	if err := in.ValidateAll(); err != nil {
		return &user.CreateResponse{
			Msg: err.Error(),
		}, nil
	}

	return &user.CreateResponse{
		Msg: "Ok",
	}, nil
}

中间件调用参数校验

引用自:validator.go

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)
	svr := server.NewUserServer(ctx)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		user.RegisterUserServer(grpcServer, svr)

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	// 中间件调用验证方式
	s.AddUnaryInterceptors(validate.UnaryServerInterceptor())

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}