Skip to content

anoyah/go-zero-validate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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()
}

About

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

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published