热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

gRPC集成protocgenvalidate

protoc-gen-validate简介安装和配置Linux执行makebuild之前需要先切换到protoc-gen-validate路径下;因为makebuild执行的

protoc-gen-validate简介


安装和配置


Linux

执行make build之前需要先切换到protoc-gen-validate路径下;因为make build执行的就是这个路径下的Makefile;一定要确保在对应的路径下,这样make build才不会出错

# fetches this repo into $GOPATH
go get -d github.com/envoyproxy/protoc-gen-validate# installs PGV into $GOPATH/bin
make build

Windows

0.6.7版本exe下载地址
最新版本exe(页面查找)
下载完成后需要将exe文件拷贝到 go的根补录的bin目录下


代码


proto


hello.proto

syntax = "proto3";
option go_package = ".;proto";
import "validate.proto";service Greeter{rpc SayHello(Person) returns (Person);
}message Person {uint64 id = 1 [(validate.rules).uint64.gt = 999];string email = 2 [(validate.rules).string.email = true];string name = 3 [(validate.rules).string = {pattern: "[\u4e00-\u9fa5]",max_bytes: 30,}];Location home = 4 [(validate.rules).message.required = true];message Location {double lat = 1 [(validate.rules).double = {gte: -90, lte: 90}];double lng = 2 [(validate.rules).double = {gte: -180, lte: 180}];}
}

validate.proto

validate.proto再hello.proto有引用;可以直接再validate.protocopy出来一份放到与hello.proto的同级目录下,也可以直接复制下面的代码

syntax = "proto2";
package validate;option go_package = "github.com/envoyproxy/protoc-gen-validate/validate";
option java_package = "io.envoyproxy.pgv.validate";import "google/protobuf/descriptor.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";// Validation rules applied at the message level
extend google.protobuf.MessageOptions {// Disabled nullifies any validation rules for this message, including any// message fields associated with it that do support validation.optional bool disabled = 1071;// Ignore skips generation of validation methods for this message.optional bool ignored = 1072;
}// Validation rules applied at the oneof level
extend google.protobuf.OneofOptions {// Required ensures that exactly one the field options in a oneof is set;// validation fails if no fields in the oneof are set.optional bool required = 1071;
}// Validation rules applied at the field level
extend google.protobuf.FieldOptions {// Rules specify the validations to be performed on this field. By default,// no validation is performed against a field.optional FieldRules rules = 1071;
}// FieldRules encapsulates the rules for each type of field. Depending on the
// field, the correct set should be used to ensure proper validations.
message FieldRules {optional MessageRules message = 17;oneof type {// Scalar Field TypesFloatRules float = 1;DoubleRules double = 2;Int32Rules int32 = 3;Int64Rules int64 = 4;UInt32Rules uint32 = 5;UInt64Rules uint64 = 6;SInt32Rules sint32 = 7;SInt64Rules sint64 = 8;Fixed32Rules fixed32 = 9;Fixed64Rules fixed64 = 10;SFixed32Rules sfixed32 = 11;SFixed64Rules sfixed64 = 12;BoolRules bool = 13;StringRules string = 14;BytesRules bytes = 15;// Complex Field TypesEnumRules enum = 16;RepeatedRules repeated = 18;MapRules map = 19;// Well-Known Field TypesAnyRules any = 20;DurationRules duration = 21;TimestampRules timestamp = 22;}
}// FloatRules describes the constraints applied to `float` values
message FloatRules {// Const specifies that this field must be exactly the specified valueoptional float const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional float lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional float lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional float gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional float gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated float in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated float not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// DoubleRules describes the constraints applied to `double` values
message DoubleRules {// Const specifies that this field must be exactly the specified valueoptional double const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional double lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional double lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional double gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional double gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated double in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated double not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// Int32Rules describes the constraints applied to `int32` values
message Int32Rules {// Const specifies that this field must be exactly the specified valueoptional int32 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional int32 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional int32 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional int32 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional int32 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated int32 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated int32 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// Int64Rules describes the constraints applied to `int64` values
message Int64Rules {// Const specifies that this field must be exactly the specified valueoptional int64 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional int64 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional int64 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional int64 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional int64 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated int64 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated int64 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// UInt32Rules describes the constraints applied to `uint32` values
message UInt32Rules {// Const specifies that this field must be exactly the specified valueoptional uint32 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional uint32 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional uint32 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional uint32 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional uint32 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated uint32 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated uint32 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// UInt64Rules describes the constraints applied to `uint64` values
message UInt64Rules {// Const specifies that this field must be exactly the specified valueoptional uint64 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional uint64 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional uint64 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional uint64 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional uint64 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated uint64 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated uint64 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// SInt32Rules describes the constraints applied to `sint32` values
message SInt32Rules {// Const specifies that this field must be exactly the specified valueoptional sint32 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional sint32 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional sint32 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional sint32 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional sint32 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated sint32 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated sint32 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// SInt64Rules describes the constraints applied to `sint64` values
message SInt64Rules {// Const specifies that this field must be exactly the specified valueoptional sint64 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional sint64 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional sint64 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional sint64 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional sint64 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated sint64 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated sint64 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// Fixed32Rules describes the constraints applied to `fixed32` values
message Fixed32Rules {// Const specifies that this field must be exactly the specified valueoptional fixed32 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional fixed32 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional fixed32 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional fixed32 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional fixed32 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated fixed32 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated fixed32 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// Fixed64Rules describes the constraints applied to `fixed64` values
message Fixed64Rules {// Const specifies that this field must be exactly the specified valueoptional fixed64 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional fixed64 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional fixed64 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional fixed64 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional fixed64 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated fixed64 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated fixed64 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// SFixed32Rules describes the constraints applied to `sfixed32` values
message SFixed32Rules {// Const specifies that this field must be exactly the specified valueoptional sfixed32 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional sfixed32 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional sfixed32 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional sfixed32 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional sfixed32 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated sfixed32 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated sfixed32 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// SFixed64Rules describes the constraints applied to `sfixed64` values
message SFixed64Rules {// Const specifies that this field must be exactly the specified valueoptional sfixed64 const = 1;// Lt specifies that this field must be less than the specified value,// exclusiveoptional sfixed64 lt = 2;// Lte specifies that this field must be less than or equal to the// specified value, inclusiveoptional sfixed64 lte = 3;// Gt specifies that this field must be greater than the specified value,// exclusive. If the value of Gt is larger than a specified Lt or Lte, the// range is reversed.optional sfixed64 gt = 4;// Gte specifies that this field must be greater than or equal to the// specified value, inclusive. If the value of Gte is larger than a// specified Lt or Lte, the range is reversed.optional sfixed64 gte = 5;// In specifies that this field must be equal to one of the specified// valuesrepeated sfixed64 in = 6;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated sfixed64 not_in = 7;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 8;
}// BoolRules describes the constraints applied to `bool` values
message BoolRules {// Const specifies that this field must be exactly the specified valueoptional bool const = 1;
}// StringRules describe the constraints applied to `string` values
message StringRules {// Const specifies that this field must be exactly the specified valueoptional string const = 1;// Len specifies that this field must be the specified number of// characters (Unicode code points). Note that the number of// characters may differ from the number of bytes in the string.optional uint64 len = 19;// MinLen specifies that this field must be the specified number of// characters (Unicode code points) at a minimum. Note that the number of// characters may differ from the number of bytes in the string.optional uint64 min_len = 2;// MaxLen specifies that this field must be the specified number of// characters (Unicode code points) at a maximum. Note that the number of// characters may differ from the number of bytes in the string.optional uint64 max_len = 3;// LenBytes specifies that this field must be the specified number of bytesoptional uint64 len_bytes = 20;// MinBytes specifies that this field must be the specified number of bytes// at a minimumoptional uint64 min_bytes = 4;// MaxBytes specifies that this field must be the specified number of bytes// at a maximumoptional uint64 max_bytes = 5;// Pattern specifes that this field must match against the specified// regular expression (RE2 syntax). The included expression should elide// any delimiters.optional string pattern = 6;// Prefix specifies that this field must have the specified substring at// the beginning of the string.optional string prefix = 7;// Suffix specifies that this field must have the specified substring at// the end of the string.optional string suffix = 8;// Contains specifies that this field must have the specified substring// anywhere in the string.optional string contains = 9;// NotContains specifies that this field cannot have the specified substring// anywhere in the string.optional string not_contains = 23;// In specifies that this field must be equal to one of the specified// valuesrepeated string in = 10;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated string not_in = 11;// WellKnown rules provide advanced constraints against common string// patternsoneof well_known {// Email specifies that the field must be a valid email address as// defined by RFC 5322bool email = 12;// Hostname specifies that the field must be a valid hostname as// defined by RFC 1034. This constraint does not support// internationalized domain names (IDNs).bool hostname = 13;// Ip specifies that the field must be a valid IP (v4 or v6) address.// Valid IPv6 addresses should not include surrounding square brackets.bool ip = 14;// Ipv4 specifies that the field must be a valid IPv4 address.bool ipv4 = 15;// Ipv6 specifies that the field must be a valid IPv6 address. Valid// IPv6 addresses should not include surrounding square brackets.bool ipv6 = 16;// Uri specifies that the field must be a valid, absolute URI as defined// by RFC 3986bool uri = 17;// UriRef specifies that the field must be a valid URI as defined by RFC// 3986 and may be relative or absolute.bool uri_ref = 18;// Address specifies that the field must be either a valid hostname as// defined by RFC 1034 (which does not support internationalized domain// names or IDNs), or it can be a valid IP (v4 or v6).bool address = 21;// Uuid specifies that the field must be a valid UUID as defined by// RFC 4122bool uuid = 22;// WellKnownRegex specifies a common well known pattern defined as a regex.KnownRegex well_known_regex = 24;}// This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable// strict header validation.// By default, this is true, and HTTP header validations are RFC-compliant.// Setting to false will enable a looser validations that only disallows// \r\n\0 characters, which can be used to bypass header matching rules.optional bool strict = 25 [default = true];// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 26;
}// WellKnownRegex contain some well-known patterns.
enum KnownRegex {UNKNOWN = 0;// HTTP header name as defined by RFC 7230.HTTP_HEADER_NAME = 1;// HTTP header value as defined by RFC 7230.HTTP_HEADER_VALUE = 2;
}// BytesRules describe the constraints applied to `bytes` values
message BytesRules {// Const specifies that this field must be exactly the specified valueoptional bytes const = 1;// Len specifies that this field must be the specified number of bytesoptional uint64 len = 13;// MinLen specifies that this field must be the specified number of bytes// at a minimumoptional uint64 min_len = 2;// MaxLen specifies that this field must be the specified number of bytes// at a maximumoptional uint64 max_len = 3;// Pattern specifes that this field must match against the specified// regular expression (RE2 syntax). The included expression should elide// any delimiters.optional string pattern = 4;// Prefix specifies that this field must have the specified bytes at the// beginning of the string.optional bytes prefix = 5;// Suffix specifies that this field must have the specified bytes at the// end of the string.optional bytes suffix = 6;// Contains specifies that this field must have the specified bytes// anywhere in the string.optional bytes contains = 7;// In specifies that this field must be equal to one of the specified// valuesrepeated bytes in = 8;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated bytes not_in = 9;// WellKnown rules provide advanced constraints against common byte// patternsoneof well_known {// Ip specifies that the field must be a valid IP (v4 or v6) address in// byte formatbool ip = 10;// Ipv4 specifies that the field must be a valid IPv4 address in byte// formatbool ipv4 = 11;// Ipv6 specifies that the field must be a valid IPv6 address in byte// formatbool ipv6 = 12;}// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 14;
}// EnumRules describe the constraints applied to enum values
message EnumRules {// Const specifies that this field must be exactly the specified valueoptional int32 const = 1;// DefinedOnly specifies that this field must be only one of the defined// values for this enum, failing on any undefined value.optional bool defined_only = 2;// In specifies that this field must be equal to one of the specified// valuesrepeated int32 in = 3;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated int32 not_in = 4;
}// MessageRules describe the constraints applied to embedded message values.
// For message-type fields, validation is performed recursively.
message MessageRules {// Skip specifies that the validation rules of this field should not be// evaluatedoptional bool skip = 1;// Required specifies that this field must be setoptional bool required = 2;
}// RepeatedRules describe the constraints applied to `repeated` values
message RepeatedRules {// MinItems specifies that this field must have the specified number of// items at a minimumoptional uint64 min_items = 1;// MaxItems specifies that this field must have the specified number of// items at a maximumoptional uint64 max_items = 2;// Unique specifies that all elements in this field must be unique. This// contraint is only applicable to scalar and enum types (messages are not// supported).optional bool unique = 3;// Items specifies the contraints to be applied to each item in the field.// Repeated message fields will still execute validation against each item// unless skip is specified here.optional FieldRules items = 4;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 5;
}// MapRules describe the constraints applied to `map` values
message MapRules {// MinPairs specifies that this field must have the specified number of// KVs at a minimumoptional uint64 min_pairs = 1;// MaxPairs specifies that this field must have the specified number of// KVs at a maximumoptional uint64 max_pairs = 2;// NoSparse specifies values in this field cannot be unset. This only// applies to map's with message value types.optional bool no_sparse = 3;// Keys specifies the constraints to be applied to each key in the field.optional FieldRules keys = 4;// Values specifies the constraints to be applied to the value of each key// in the field. Message values will still have their validations evaluated// unless skip is specified here.optional FieldRules values = 5;// IgnoreEmpty specifies that the validation rules of this field should be// evaluated only if the field is not emptyoptional bool ignore_empty = 6;
}// AnyRules describe constraints applied exclusively to the
// `google.protobuf.Any` well-known type
message AnyRules {// Required specifies that this field must be setoptional bool required = 1;// In specifies that this field's `type_url` must be equal to one of the// specified values.repeated string in = 2;// NotIn specifies that this field's `type_url` must not be equal to any of// the specified values.repeated string not_in = 3;
}// DurationRules describe the constraints applied exclusively to the
// `google.protobuf.Duration` well-known type
message DurationRules {// Required specifies that this field must be setoptional bool required = 1;// Const specifies that this field must be exactly the specified valueoptional google.protobuf.Duration const = 2;// Lt specifies that this field must be less than the specified value,// exclusiveoptional google.protobuf.Duration lt = 3;// Lt specifies that this field must be less than the specified value,// inclusiveoptional google.protobuf.Duration lte = 4;// Gt specifies that this field must be greater than the specified value,// exclusiveoptional google.protobuf.Duration gt = 5;// Gte specifies that this field must be greater than the specified value,// inclusiveoptional google.protobuf.Duration gte = 6;// In specifies that this field must be equal to one of the specified// valuesrepeated google.protobuf.Duration in = 7;// NotIn specifies that this field cannot be equal to one of the specified// valuesrepeated google.protobuf.Duration not_in = 8;
}// TimestampRules describe the constraints applied exclusively to the
// `google.protobuf.Timestamp` well-known type
message TimestampRules {// Required specifies that this field must be setoptional bool required = 1;// Const specifies that this field must be exactly the specified valueoptional google.protobuf.Timestamp const = 2;// Lt specifies that this field must be less than the specified value,// exclusiveoptional google.protobuf.Timestamp lt = 3;// Lte specifies that this field must be less than the specified value,// inclusiveoptional google.protobuf.Timestamp lte = 4;// Gt specifies that this field must be greater than the specified value,// exclusiveoptional google.protobuf.Timestamp gt = 5;// Gte specifies that this field must be greater than the specified value,// inclusiveoptional google.protobuf.Timestamp gte = 6;// LtNow specifies that this must be less than the current time. LtNow// can only be used with the Within rule.optional bool lt_now = 7;// GtNow specifies that this must be greater than the current time. GtNow// can only be used with the Within rule.optional bool gt_now = 8;// Within specifies that this field must be within this duration of the// current time. This constraint can be used alone or with the LtNow and// GtNow rules.optional google.protobuf.Duration within = 9;
}

使用命令生成对应的go代码

protoc -I . --go_out=plugins=grpc:. --validate_out="lang=go:." hello.proto

生成代码的时候如果遇到 ‘protoc-gen-validate’ 不是内部或外部命令,也不是可运行的程序这种错,就需要检查一下下载的exe是否放置到了go的根补录的bin目录下或者看一下下载的exe文件名是否带有版本号;例如:
在这里插入图片描述
如果有带有类似的版本号就将exe名称后面的版本号删除掉就可以了

在这里插入图片描述


.pb.go

对应的代码篇幅过长,这里进行省略,只要正常输入命令生成就好.


Server

package mainimport ("ShopBefore/rpc/grpc_validate/proto""context""google.golang.org/grpc""google.golang.org/grpc/codes""google.golang.org/grpc/status""net"
)type Server struct{}func (s Server) SayHello(ctx context.Context, person *proto.Person) (*proto.Person, error) {return &proto.Person{Id: 999}, nil
}type Validator interface {Validate() error
}func main() {interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {// 使用Validator不使用Person;是为了避免硬编码// 这样拦截器每个需要验证的req都可以使用if p, ok := req.(Validator); ok {if err := p.Validate(); err != nil {// 参数没有通过验证时;返回一个错误不继续向下执行return nil, status.Error(codes.InvalidArgument, err.Error())}}// 通过验证后继续向下执行return handler(ctx, req)}server := grpc.NewServer(grpc.UnaryInterceptor(interceptor))proto.RegisterGreeterServer(server,&Server{})listen, _ := net.Listen("tcp", ":8081")_ = server.Serve(listen)
}

Client

package mainimport ("ShopBefore/rpc/grpc_validate/proto""context""fmt""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure""log"
)func main() {conn, _ := grpc.Dial("localhost:8081", grpc.WithTransportCredentials(insecure.NewCredentials()))defer conn.Close()client := proto.NewGreeterClient(conn)res, err := client.SayHello(context.Background(), &proto.Person{Id: 1000,Email: "fanqiechaodan@fanqiechaodan.com",Name: "番茄炒蛋",Home: &proto.Person_Location{Lat: 23,Lng: 45,},})if err != nil {log.Println(err.Error())}fmt.Println(res.Id)
}

每次当Server收到请求后,都会根据我们提前再proto文件中设置的规则进行校验;如果参数不符合预设的规则会相应的返回给客户端对应的错误;代码中的部分error为了编写效率没有处理请忽略;


备注

在这里插入图片描述
文档中有标记该项目目前处于alpha 阶段。API 应被视为不稳定且可能会更改;个人建议再现阶段使用还是要谨慎使用


推荐阅读
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
  • Python操作MySQL(pymysql模块)详解及示例代码
    本文介绍了使用Python操作MySQL数据库的方法,详细讲解了pymysql模块的安装和连接MySQL数据库的步骤,并提供了示例代码。内容涵盖了创建表、插入数据、查询数据等操作,帮助读者快速掌握Python操作MySQL的技巧。 ... [详细]
  • python3连接外部Mysql
    前提条件,已经安装过MySQL(比如说以前web开发安装过MySQL)1.安装PyMySQLpipinstallPyMySQL2.测试1i ... [详细]
  • 本文介绍了Python对Excel文件的读取方法,包括模块的安装和使用。通过安装xlrd、xlwt、xlutils、pyExcelerator等模块,可以实现对Excel文件的读取和处理。具体的读取方法包括打开excel文件、抓取所有sheet的名称、定位到指定的表单等。本文提供了两种定位表单的方式,并给出了相应的代码示例。 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
  • RouterOS 5.16软路由安装图解教程
    本文介绍了如何安装RouterOS 5.16软路由系统,包括系统要求、安装步骤和登录方式。同时提供了详细的图解教程,方便读者进行操作。 ... [详细]
  • 本文详细介绍了git常用命令及其操作方法,包括查看、添加、提交、删除、找回等操作,以及如何重置修改文件、抛弃工作区修改、将工作文件提交到本地暂存区、从版本库中删除文件等。同时还介绍了如何从暂存区恢复到工作文件、恢复最近一次提交过的状态,以及如何合并多个操作等。 ... [详细]
  • Iwanttointegratesort,order,maxandoffsetinafindAllquery.Thefollowingworksfine:我想在fin ... [详细]
  • 图解 Google V8 # 19 :异步编程(二):V8 是如何实现 async/await 的?
    说明图解GoogleV8学习笔记前端异步编程的方案史1、什么是回调地狱?如果在代码中过多地使用异步回调函数,会将整个代码逻辑打乱,从 ... [详细]
  • Ihavethisfollowinginputfile:我有以下输入文件:test.csvdone_cfg,,,,port<0>,clk_in,subcktA,ins ... [详细]
  • Iamworkingonaprojectwhichrequiresopentokandcallkitfornotifyingusers.However,theappli ... [详细]
author-avatar
悠哉游_甘肃
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有