mwitkow/go-proto-validators: Generate message validators from .proto annotations. - 图1
mwitkow/go-proto-validators: Generate message validators from .proto annotations. - 图2

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.

Requirements

Using Protobuf validators is currently verified to work with:

It 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.

Paint me a code picture

Let’s take the following proto3 snippet:

  1. syntax = "proto3";
  2. package validator.examples;
  3. import "github.com/mwitkow/go-proto-validators/validator.proto";
  4. message InnerMessage {
  5. // some_integer can only be in range (0, 100).
  6. int32 some_integer = 1 [(validator.field) = {int_gt: 0, int_lt: 100}];
  7. // some_float can only be in range (0;1).
  8. double some_float = 2 [(validator.field) = {float_gte: 0, float_lte: 1}];
  9. }
  10. message OuterMessage {
  11. // important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax).
  12. string important_string = 1 [(validator.field) = {regex: "^[a-z0-9]{5,30}$"}];
  13. // proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage.
  14. InnerMessage inner = 2 [(validator.field) = {msg_exists : true}];
  15. }

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:

  1. func (this *InnerMessage) Validate() error {
  2. if !(this.SomeInteger > 0) {
  3. return fmt.Errorf("validation error: InnerMessage.SomeInteger must be greater than '0'")
  4. }
  5. if !(this.SomeInteger < 100) {
  6. return fmt.Errorf("validation error: InnerMessage.SomeInteger must be less than '100'")
  7. }
  8. if !(this.SomeFloat >= 0) {
  9. return fmt.Errorf("validation error: InnerMessage.SomeFloat must be greater than or equal to '0'")
  10. }
  11. if !(this.SomeFloat <= 1) {
  12. return fmt.Errorf("validation error: InnerMessage.SomeFloat must be less than or equal to '1'")
  13. }
  14. return nil
  15. }
  16. var _regex_OuterMessage_ImportantString = regexp.MustCompile("^[a-z0-9]{5,30}$")
  17. func (this *OuterMessage) Validate() error {
  18. if !_regex_OuterMessage_ImportantString.MatchString(this.ImportantString) {
  19. return fmt.Errorf("validation error: OuterMessage.ImportantString must conform to regex '^[a-z0-9]{5,30}$'")
  20. }
  21. if nil == this.Inner {
  22. return fmt.Errorf("validation error: OuterMessage.Inner message must exist")
  23. }
  24. if this.Inner != nil {
  25. if err := validators.CallValidatorIfExists(this.Inner); err != nil {
  26. return err
  27. }
  28. }
  29. return nil
  30. }

Installing and using

The protoc compiler expects to find plugins named proto-gen-XYZ on the execution $PATH. So first:

  1. export PATH=${PATH}:${GOPATH}/bin

Then, do the usual

  1. go get github.com/mwitkow/go-proto-validators/protoc-gen-govalidators

Your protoc builds probably look very simple like:

  1. protoc \
  2. --proto_path=. \
  3. --go_out=. \
  4. *.proto

That’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:

  1. protoc \
  2. --proto_path=${GOPATH}/src \
  3. --proto_path=${GOPATH}/src/github.com/google/protobuf/src \
  4. --proto_path=. \
  5. --go_out=. \
  6. --govalidators_out=. \
  7. *.proto

Or with gogo protobufs:

  1. protoc \
  2. --proto_path=${GOPATH}/src \
  3. --proto_path=${GOPATH}/src/github.com/gogo/protobuf/protobuf \
  4. --proto_path=. \
  5. --gogo_out=. \
  6. --govalidators_out=gogoimport=true:. \
  7. *.proto

Basically 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 :)

License

go-proto-validators is released under the Apache 2.0 license. See the LICENSE file for details.
https://github.com/mwitkow/go-proto-validators