Comprehensive Course for Go Engineers: protoc-gen-validate

protoc-gen-validate Introduction and Usage Guide

✅ What is protoc-gen-validate

protoc-gen-validate (short for PGV) is a Protocol Buffers plugin used to add validation logic for struct fields in generated Go code.

By adding validate rules in .proto files, it automatically generates validation code for each field, saving you from writing validation logic manually.


🌟 Example

syntax = "proto3";

import "validate/validate.proto";

message User {
  string name = 1 [(validate.rules).string.min_len = 3];
  int32 age = 2 [(validate.rules).int32.gte = 18];
}

The generated Go code will automatically include:

user := &User{Name: "Tom", Age: 16}
if err := user.Validate(); err != nil {
    // err 会指出字段不符合要求
}

✅ Supported Validation Rule Types

  • string: min_len, max_len, email, ip, uri, pattern, etc.
  • number: gte, lte, lt, gt
  • repeated: min_items, unique, items rules
  • map: min_pairs, keys rules, values rules
  • message: Nested validation
  • oneof: Sub-field validation
  • required: Whether the field is required

✅ Supported Languages

  • Go (Strongest official support)
  • C++
  • Java
  • Python
  • C#
  • Rust (via community plugin)

✅ Maturity and Usage Recommendations

Item Description
Maturity Very mature, widely used in many microservice projects (e.g., buf.build ecosystem)
Community Support Has an active community, maintenance transferred from the original author to bufbuild
Compatibility with other tools Perfectly supports protoc-gen-go, can be used with buf, grpc-gateway, govalidator, etc.
Applicable Scenarios Server-side field validation, API request validation, microservice interface parameter validation

🛠 Usage Steps (Brief)

  1. Install the plugin:
go install github.com/bufbuild/protoc-gen-validate@latest
  1. Download the proto file definitions required by PGV:
git clone https://github.com/bufbuild/protoc-gen-validate

Or use buf registry reference: buf.build/buf/validate

  1. Compile command:
protoc \
  --proto_path=./proto \
  --go_out=. \
  --go-grpc_out=. \
  --validate_out=lang=go:. \
  your_file.proto

📦 Common Alternatives

Tool Description
cel An expression language from Google, can be used for proto validation, but with slightly higher complexity
Manual validation Flexible but repetitive and error-prone
go-playground/validator General Go struct validation tool, not dependent on proto

✅ Summary

protoc-gen-validate is a mature, stable, and easy-to-use protobuf field validation solution, especially suitable for:

  • Parameter validation in microservice architectures
  • Automatic generation of validation logic
  • Project teams looking to reduce repetitive manual validation

主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/6728

(0)
Walker的头像Walker
上一篇 13 hours ago
下一篇 1 day ago

Related Posts

EN
简体中文 繁體中文 English