Protobuf Validation
This extension integrates two powerful tools for validating Protobuf messages: protovalidate and protoc-gen-validate. These tools ensure that your Protobuf messages adhere to the defined validation rules.
protovalidate
is the successor to protoc-gen-validate
, so it is recommended to use protovalidate
.
Dependencies
- protovalidate
- protoc-gen-validate
- Gradle
- Maven
implementation("io.github.danielliu1123:grpc-starter-protovalidate")
<dependency>
<groupId>io.github.danielliu1123</groupId>
<artifactId>grpc-starter-protovalidate</artifactId>
</dependency>
- Gradle
- Maven
implementation("io.github.danielliu1123:grpc-starter-validation")
<dependency>
<groupId>io.github.danielliu1123</groupId>
<artifactId>grpc-starter-validation</artifactId>
</dependency>
Example
- protovalidate
- protoc-gen-validate
Refer to protovalidate example.
syntax = "proto3";
package foo;
import "buf/validate/validate.proto";
message Foo {
string id = 1 [(buf.validate.field).cel = {
id: "id",
message: "id length must be at least 5 characters",
expression: "this.size() >= 5",
}];
string name = 2 [(buf.validate.field).string = {min_len: 5}];
repeated string hobbies = 3 [(buf.validate.field).repeated = {min_items: 1}];
option (buf.validate.message).cel = {
id: "foo",
message: "not a valid Foo",
expression: "this.name != 'programmer' && !('coding' in this.hobbies)",
};
}
service FooService {
rpc InsertFoo (Foo) returns (Foo) {}
}
Refer to validation example.
syntax = "proto3";
package foo;
import "validate/validate.proto";
message Foo {
string name = 2 [(validate.rules).string = {
min_len: 2
max_len: 10
}];
repeated string hobbies = 3 [(validate.rules).repeated = {
min_items: 1
}];
}
service FooService {
rpc InsertFoo (Foo) returns (Foo) {}
}
These validation rules will be applied to the gRPC client and server by default.
For more information about the validation rules, see protovalidate and protoc-gen-validate
Configurations
If you want to disable the validation, use the following configuration:
grpc:
validation:
enabled: false # disable the validation for client and server
Only disable the validation for the client:
grpc:
validation:
client:
enabled: false
Only disable the validation for the server:
grpc:
validation:
server:
enabled: false
The verification processing is implemented through ClientInterceptor
and ServerInterceptor
.
The order of interceptors can be customized.
The default order is 0.
grpc:
validation:
client:
order: 0
server:
order: 0