Validate
First you should install proto-gen-validate
Example
Here are some examples of parameter validation for several common situations, you may also refer to more examples in proto-gen-validate
// id must be greater than 0
// age must be in the range (0, 120]
int32 age = 2 [(validate.rules).int64 = {gt:0, lte: 120}];
// code must be either 1, 2, or 3
uint32 code = 3 [(validate.rules).uint32 = {in: [1,2,3]}];
// score cannot be 0 nor 0.99
float score = 1 [(validate.rules).float = {not_in: [0, 99.99]}];
Bools
bool state = 5 [(validate.rules).bool.const = true];
// x cannot be set to true
bool state = 5 [(validate.rules).bool.const = false];
Strings
Messages
// info cannot be unset
Info info = 11 [(validate.rules).message.required = true];
string address = 1;
}
Code Generation
protoc --proto_path=. \
--go_out=paths=source_relative:. \
--validate_out=paths=source_relative,lang=go:. \
xxxx.proto
2.Add the validate
command in Makefile
make validate
We can inject the validate middleware into HTTP or gRPC, and the validate middleware automatically validates the parameters according to the rules written in the proto when request entering.
HTTP
httpSrv := http.NewServer(
http.Address(":8000"),
http.Middleware(
validate.Validator(),