🙆‍♀️

protoc-gen-validate

2023/08/08に公開

https://github.com/bufbuild/protoc-gen-validate

protoc-gen-validateは、protoファイルのvalidationを行うプラグインです。

Code Sample

example.proto
syntax = "proto3";

package examplepb;

import "validate/validate.proto";

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:   "^[^[0-9]A-Za-z]+( [^[0-9]A-Za-z]+)*$",
    max_bytes: 256,
  }];

  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}];
  }
}
main.go
p := new(Person)

err := p.Validate() // err: Id must be greater than 999
p.Id = 1000

err = p.Validate() // err: Email must be a valid email address
p.Email = "example@bufbuild.com"

err = p.Validate() // err: Name must match pattern '^[^\d\s]+( [^\d\s]+)*$'
p.Name = "Protocol Buffer"

err = p.Validate() // err: Home is required
p.Home = &Location{37.7, 999}

err = p.Validate() // err: Home.Lng must be within [-180, 180]
p.Home.Lng = -122.4

err = p.Validate() // err: nil

Installation

go get -d github.com/envoyproxy/protoc-gen-validate

Examples

buf.gen.yaml
version: v1
plugins:
  - plugin: buf.build/bufbuild/validate-go
    out: gen
    opt: paths=source_relative
buf.yaml
version: v1
deps:
  - buf.build/envoyproxy/protoc-gen-validate

Usage

buf lint
buf generate

これで、validationのコードが自動生成されます。

Discussion