Generate message validators from .proto annotations.
Generate message validators from .proto annotations.
A protoc plugin that generates Validate() error functions on Go proto structs based on field options inside .proto
files. The validation functions are code-generated and thus don't suffer on performance from tag-based reflection on
deeply-nested messages.
Using Protobuf validators is currently verified to work with:
v3.8.0v1.3.2v1.3.0It should still be possible to use it in project using earlier Go versions. However if you want to contribute to this repository you'll need at least 1.11 for Go module support.
Let's take the following proto3 snippet:
…First, the required keyword is back for proto3, under the guise of msg_exists. The painful if-nil checks are taken care of!
Second, the expected values in fields are now part of the contract .proto file. No more hunting down conditions in code!
Third, the generated code is understandable and has clear understandable error messages. Take a look:
…The protoc compiler expects to find plugins named proto-gen-XYZ on the execution $PATH. So first:
export PATH=${PATH}:${GOPATH}/binThen, do the usual
go get github.com/mwitkow/go-proto-validators/protoc-gen-govalidatorsYour protoc builds probably look very simple like:
protoc \
--proto_path=. \
--go_out=. \
*.protoThat's fine, until you encounter .proto includes. Because go-proto-validators uses field options inside the .proto
files themselves, it's .proto definition (and the Google descriptor.proto itself) need to on the protoc include
path. Hence the above becomes:
protoc \
--proto_path=${GOPATH}/src \
--proto_path=${GOPATH}/src/github.com/google/protobuf/src \
--proto_path=. \
--go_out=. \
--govalidators_out=. \
*.protoOr with gogo protobufs:
protoc \
--proto_path=${GOPATH}/src \
--proto_path=${GOPATH}/src/github.com/gogo/protobuf/protobuf \
--proto_path=. \
--gogo_out=. \
--govalidators_out=gogoimport=true:. \
*.protoBasically the magical incantation (apart from includes) is the --govalidators_out. That triggers the
protoc-gen-govalidators plugin to generate mymessage.validator.pb.go. That's it :)
go-proto-validators is released under the Apache 2.0 license. See the LICENSE file for details.
No open issues yet, or sync has not completed.