Go gRPC服务proto数据验证进阶教程
作者:烟花易冷人憔悴 发布时间:2024-03-20 16:54:54
前言
上篇介绍了go-grpc-middleware的grpc_zap、grpc_auth和grpc_recovery使用,本篇将介绍grpc_validator,它可以对gRPC数据的输入和输出进行验证。
创建proto文件,添加验证规则
这里使用第三方插件go-proto-validators自动生成验证规则。
go get github.com/mwitkow/go-proto-validators
1.新建simple.proto文件
syntax = "proto3";
package proto;
import "github.com/mwitkow/go-proto-validators/validator.proto";
message InnerMessage {
// some_integer can only be in range (1, 100).
int32 some_integer = 1 [(validator.field) = {int_gt: 0, int_lt: 100}];
// some_float can only be in range (0;1).
double some_float = 2 [(validator.field) = {float_gte: 0, float_lte: 1}];
}
message OuterMessage {
// important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax).
string important_string = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}];
// proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage.
InnerMessage inner = 2 [(validator.field) = {msg_exists : true}];
}
service Simple{
rpc Route (InnerMessage) returns (OuterMessage){};
}
代码import "github.com/mwitkow/go-proto-validators/validator.proto",文件validator.proto需要import "google/protobuf/descriptor.proto";包,不然会报错。
google/protobuf地址:
https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto
把src文件夹中的protobuf目录下载到GOPATH目录下。
2.编译simple.proto文件
go get github.com/mwitkow/go-proto-validators/protoc-gen-govalidators
指令编译:
protoc --govalidators_out=. --go_out=plugins=grpc:./ ./simple.proto
或者使用VSCode-proto3插件,第一篇有介绍。只需要添加"--govalidators_out=."即可。
// vscode-proto3插件配置
"protoc": {
// protoc.exe所在目录
"path": "C:\\Go\\bin\\protoc.exe",
// 保存时自动编译
"compile_on_save": true,
"options": [
// go编译输出指令
"--go_out=plugins=grpc:.",
"--govalidators_out=."
]
},
编译完成后,自动生成simple.pb.go和simple.validator.pb.go文件,simple.pb.go文件不再介绍,我们看下simple.validator.pb.go文件。
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: go-grpc-example/9-grpc_proto_validators/proto/simple.proto
package proto
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
_ "github.com/mwitkow/go-proto-validators"
regexp "regexp"
github_com_mwitkow_go_proto_validators "github.com/mwitkow/go-proto-validators"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
func (this *InnerMessage) Validate() error {
if !(this.SomeInteger > 0) {
return github_com_mwitkow_go_proto_validators.FieldError("SomeInteger", fmt.Errorf(`value '%v' must be greater than '0'`, this.SomeInteger))
}
if !(this.SomeInteger < 100) {
return github_com_mwitkow_go_proto_validators.FieldError("SomeInteger", fmt.Errorf(`value '%v' must be less than '100'`, this.SomeInteger))
}
if !(this.SomeFloat >= 0) {
return github_com_mwitkow_go_proto_validators.FieldError("SomeFloat", fmt.Errorf(`value '%v' must be greater than or equal to '0'`, this.SomeFloat))
}
if !(this.SomeFloat <= 1) {
return github_com_mwitkow_go_proto_validators.FieldError("SomeFloat", fmt.Errorf(`value '%v' must be lower than or equal to '1'`, this.SomeFloat))
}
return nil
}
var _regex_OuterMessage_ImportantString = regexp.MustCompile(`^[a-z]{2,5}$`)
func (this *OuterMessage) Validate() error {
if !_regex_OuterMessage_ImportantString.MatchString(this.ImportantString) {
return github_com_mwitkow_go_proto_validators.FieldError("ImportantString", fmt.Errorf(`value '%v' must be a string conforming to regex "^[a-z]{2,5}$"`, this.ImportantString))
}
if nil == this.Inner {
return github_com_mwitkow_go_proto_validators.FieldError("Inner", fmt.Errorf("message must exist"))
}
if this.Inner != nil {
if err := github_com_mwitkow_go_proto_validators.CallValidatorIfExists(this.Inner); err != nil {
return github_com_mwitkow_go_proto_validators.FieldError("Inner", err)
}
}
return nil
}
里面自动生成了message中属性的验证规则。
把grpc_validator验证 * 添加到服务端
grpcServer := grpc.NewServer(cred.TLSInterceptor(),
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
grpc_validator.StreamServerInterceptor(),
grpc_auth.StreamServerInterceptor(auth.AuthInterceptor),
grpc_zap.StreamServerInterceptor(zap.ZapInterceptor()),
grpc_recovery.StreamServerInterceptor(recovery.RecoveryInterceptor()),
)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_validator.UnaryServerInterceptor(),
grpc_auth.UnaryServerInterceptor(auth.AuthInterceptor),
grpc_zap.UnaryServerInterceptor(zap.ZapInterceptor()),
grpc_recovery.UnaryServerInterceptor(recovery.RecoveryInterceptor()),
)),
)
运行后,当输入数据验证失败后,会有以下错误返回
Call Route err: rpc error: code = InvalidArgument desc = invalid field SomeInteger: value '101' must be less than '100'
其他类型验证规则设置
enum验证
syntax = "proto3";
package proto;
import "github.com/mwitkow/go-proto-validators/validator.proto";
message SomeMsg {
Action do = 1 [(validator.field) = {is_in_enum : true}];
}
enum Action {
ALLOW = 0;
DENY = 1;
CHILL = 2;
}
UUID验证
syntax = "proto3";
package proto;
import "github.com/mwitkow/go-proto-validators/validator.proto";
message UUIDMsg {
// user_id must be a valid version 4 UUID.
string user_id = 1 [(validator.field) = {uuid_ver: 4, string_not_empty: true}];
}
来源:https://www.cnblogs.com/FireworksEasyCool/p/12761033.html
猜你喜欢
- php二维数组排序测试数据 $arr = [
- 1 前言Python开发网络爬虫获取网页数据的基本流程为:发起请求通过URL向服务器发起request请求,请求可以包含额外的header信
- 问题:MySQL某个表自增id溢出导致某业务block背景: tokudb引擎的一个大表tb1,存放业务
- <% class menusPublic Title, ID, Image, TitleColor, Target, Backgrou
- SocketServer简化了网络服务器的编写。它有4个类:TCPServer,UDPServer,UnixStreamServer,Uni
- 1,首先是视频数据[摄像头图像]的采集,通常可以使用vfw在vc或者vb下实现,这个库我用的不好,所以一直不怎么会用.现在我们用到的是pyt
- 遇到mysql ERROR 1045 这个问题搞了很久,自己记下来。方法是百度的,亲测有效。ERROR 1045 (28000): Acce
- urllib 是 python 的内置模块, 主要用于处理url相关的一些操作,例如访问url、解析url等操作。urllib 包下面的 r
- 一、标签语法由%}和 {% 来定义的,例如:{%tag%} {%endtag%},完整的标签有开始就有结束,如条件语句,有条件判断的开始,也
- 这里先解释一下几个概念 - 位置参数:按位置设置的参数,隐式用元组保存对应形参.平时我们用的大多数是按位置传参.比如有函数def func(
- GraphSAGE是一种用于图神经网络中的节点嵌入学习方法。它通过聚合节点邻居的信息来生成节点的低维表示,使节点表示能够更好地应用于各种下游
- 换用非默认浏览器时需要输入密码或token查询方法:在XX:\AnacondaXX\Scripts下 运行jupyter-notebook.
- 本文实例讲述了Python去除列表中重复元素的方法。分享给大家供大家参考。具体如下:比较容易记忆的是用内置的setl1 = ['b&
- 本文实例讲述了python修改操作系统时间的方法。分享给大家供大家参考。具体实现方法如下:#-*- coding:utf-8 -*-impo
- 双向RNN:bidirectional_dynamic_rnn()函数的使用详解先说下为什么要使用到双向RNN,在读一篇文章的时候,上文提到
- 语法结构: 1. Cast 语法结构:CAST ( expression AS data_type [ ( length ) ] ) 2.
- 有些人说py中有两个函数可以实现对所有函数的了解以及使用,其中之一,就是我们今天要讲解的help函数。有些小伙伴可能比较陌生,但是另一个函数
- 1、重装后启动mysql服务,提示 本地计算机无法启动 mysql 服务 错误 1067:进程意外终止。2、查看mysql根目录下有一 计算
- 本文实例讲述了PHP实现数组根据某个字段进行水平合并,横向合并。分享给大家供大家参考,具体如下:PHP数组水平合并,横向合并,两条数据合并成
- 有时会在存储过程中处理一些XML格式的数据,所以会用到sp_xml_preparedocument,他可以将XML数据进行读取,然后使用 M