# proto-generator **Repository Path**: xgo-core/proto-generator ## Basic Information - **Project Name**: proto-generator - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-04-23 - **Last Updated**: 2026-10-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # proto-generator [English](./README.md) 一个 Go 库,通过调用 `protoc` 从 `.proto` 文件自动生成 Go 和 gRPC 代码,并支持通过注释注解驱动额外的代码生成。 ## 1. 功能特性 - 递归扫描目录下的所有 `.proto` 文件 - 生成 Go protobuf 绑定(`--go_out`)和 gRPC 服务桩代码(`--go-grpc_out`) - 解析 proto 注释中的注解,驱动额外的代码生成 - 内置注解:``、``、``、``、``、``、``、``、``、``、``、``、``、`` - 通过 `Annotations` 选择执行注解处理器分组:`all`、`base`、`app` 或 `doc` - 自动向所有 `.pb.go` struct 字段注入 `xml`、`form`、`uri` tag - 自动去除重复的枚举常量前缀(如 `MyEnum_MyEnum_VALUE` → `MyEnum_VALUE`) - 可扩展的 Handler 架构 — 无需修改现有代码即可添加新注解 ## 2. 环境要求 - Go 1.21+ - [`protoc`](https://grpc.io/docs/protoc-installation/) — Protocol Buffer 编译器 - [`protoc-gen-go`](https://pkg.go.dev/google.golang.org/protobuf/cmd/protoc-gen-go) - [`protoc-gen-go-grpc`](https://pkg.go.dev/google.golang.org/grpc/cmd/protoc-gen-go-grpc) - [`protoc-gen-doc`](https://github.com/pseudomuto/protoc-gen-doc) — 内部用于提取注解元数据 ```bash go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest go install github.com/pseudomuto/protoc-gen-doc/cmd/protoc-gen-doc@latest ``` ## 3. 安装 ```bash go get gitee.com/xgo-core/proto-generator ``` ## 4. 使用示例 ```go package main import ( "log" "gitee.com/xgo-core/proto-generator" ) func main() { err := pbgenerator.Generate(pbgenerator.GeneratorParam{ AppName: "app", // 必填;用于生成 import 别名 ProtoPath: "./proto", // 包含 .proto 文件的目录(递归扫描) ProtoBasePath: "./proto", // (可选)protoc 的 --proto_path 根目录;默认使用 ProtoPath OutputPath: "./gen", // 生成的 Go 文件输出目录 RoutePath: "./gen/route", // (可选)路由聚合文件 ServicePath: "./service", // (可选)service 脚手架文件 ControllerPath: "./controller", // (可选)HTTP/gRPC controller 文件 MiddlewarePath: "./middleware", // (可选)middleware 实现脚手架文件 AutoloadPath: "./autoload", // (可选)container 自动注入文件 DocPath: "./docs", // (可选)OpenAPI 文档输出目录 Annotations: []string{"all"}, // (可选)执行全部内置注解分组 }) if err != nil { log.Fatal(err) } } ``` ## 5. API ### 5.1 `GeneratorParam` | 字段 | 类型 | 说明 | |---|---|---| | `AppName` | `string` | 必填应用名称,用于生成 `AppHTTPController` 这类 import 别名 | | `ProtoPath` | `string` | 递归扫描 `.proto` 文件的根目录 | | `ProtoBasePath` | `string` | 传递给 protoc 的 `--proto_path` 根目录;默认使用 `ProtoPath` | | `OutputPath` | `string` | 生成的 Go 和 gRPC 绑定文件输出目录 | | `RoutePath` | `string` | `route.go`、`controller.go`、`middleware.go` 的生成目录 | | `ServicePath` | `string` | service 脚手架文件的生成目录 | | `ControllerPath` | `string` | HTTP/gRPC controller 文件的生成目录 | | `MiddlewarePath` | `string` | middleware 实现脚手架文件的生成目录 | | `AutoloadPath` | `string` | container 自动注入文件的生成目录 | | `DocPath` | `string` | OpenAPI 文档生成目录。非空且选中 `doc` 分组时,会为每个 HTTP service 生成 `//.json` | | `Annotations` | `[]string` | 要执行的注解处理器分组。为空或 `[]string{"all"}` 时执行全部分组 | ### 5.2 注解分组 `Annotations` 控制 protoc 生成完成后执行哪些注册过的 handler 分组。内置分组如下: | 值 | 执行内容 | |---|---| | `all` 或空值 | 执行全部带分组的 handler | | `base` | `.pb.go` 与代码辅助处理:``、``、``、``、``、`` 以及 gRPC client 包装器 | | `app` | 应用脚手架:路由、controller、service、middleware、gRPC client 自动注入和 autoload 文件 | | `doc` | 为带 `` 的 service 在 `DocPath` 下生成 OpenAPI 文档 | struct tag 注入、枚举前缀去重等全局后处理属于注解流水线,会在分组 handler 执行前运行。 ### 5.3 OpenAPI 文档 设置 `DocPath` 并选中 `doc` 分组后,每个带 `` 的 service 会生成一份包含全部 RPC 路径的 OpenAPI 3.0.3 JSON 文件。RPC 上使用 `` 设置接口名称;在 service 或 RPC 上重复使用 `` 声明必传的 `string` 类型 HTTP Header。service 级 Header 会继承给全部 RPC,RPC 级 Header 会追加到当前接口。 ### 5.4 `Generate(param GeneratorParam) error` 递归遍历 `ProtoPath`,收集所有 `.proto` 文件,调用 `protoc` 在 `OutputPath` 中生成 Go 和 gRPC 绑定代码。若未找到任何 `.proto` 文件,直接返回 `nil`。 生成前,proto-generator 会清理过期的 `.go` 文件: - **`OutputPath`** — 仅清理当前收集的 `.proto` 文件中 `go_package` 选项所对应的子目录,`OutputPath` 下的其他目录不受影响。 - **`RoutePath`** — 不会清理整个目录。生成的路由文件在产出时会被覆盖,其他自定义文件会保留。 每次生成 `*_grpc.pb.go` 时,`base` 分组会在同一包目录创建或更新 `grpc_client_gen.go`。每个 service 生成一个 `GRPCClient` 包装器,其中包含 `grpc.ClientConnInterface` 字段和 `NewClient() any` 方法;文件通过模板生成并在每次生成时完整覆盖,旧声明会被清理。 以下目录**不会**被清理,因为它们包含用户可编辑的脚手架文件,或由各自 handler 管理生成文件:`RoutePath`、`ControllerPath`、`ServicePath`、`MiddlewarePath`、`AutoloadPath`、`DocPath`。 ## 6. 自动后处理 在任何注解 handler 执行之前,proto-generator 会对所有生成的 `.pb.go` 文件做两项全局处理。 ### 6.1 Struct Tag 注入 每个带有 `json` tag 的 struct 字段都会自动获得 `xml`、`form`、`uri` tag。同时,所有字段的 `omitempty` 选项会被全局移除,若需保留,使用 `` 注解单独开启。 ```go // protoc-gen-go 原始输出 Name string `protobuf:"..." json:"name,omitempty"` // tag 注入后 Name string `protobuf:"..." json:"name" xml:"name" form:"name" uri:"name"` ``` 注入的 tag 键由 `annotation.ExtraTagKeys` 控制(默认值:`["xml", "form", "uri"]`)。 ### 6.2 枚举前缀去重 当 proto 枚举值名称已包含枚举类型前缀时,protoc-gen-go 会生成重复前缀的常量。proto-generator 会自动去除多余的前缀: ```go // 去重前 MyStatus_MyStatus_ACTIVE MyStatus = 0 // 去重后 MyStatus_ACTIVE MyStatus = 0 ``` ## 7. 脚手架 ### 7.1 Service 脚手架(`ServicePath`) 设置 `ServicePath` 后,pbgenerator 会为每个 proto service 在该目录下创建一个子目录,包含 struct 文件和每个 RPC 的桩文件。文件仅在不存在时才写入,手工编辑的实现在重新生成时不会被覆盖。 **目录结构:** ``` ServicePath/ └── my_service/ ├── my_service.go // type MyService struct {} ├── create_user.go // func (s *MyService) CreateUser(...) └── get_user.go // func (s *MyService) GetUser(...) ``` **桩文件示例:** ```go package myservice import ( "context" pb "your/module/gen/mypackage" ) func (s *MyService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (rsp *pb.CreateUserReply, err error) { panic("not implemented") // TODO: Implement } ``` ### 7.2 Middleware 脚手架(`MiddlewarePath`) 设置 `MiddlewarePath` 后,pbgenerator 会为所有 `` 注解中出现的每个唯一 middleware 名称生成一个实现脚手架文件。`param` 参数可选;`` 会向 middleware 传入空字符串。`RoutePath/middleware.go` 中的聚合结构会直接引用这些具体实现。 文件仅在不存在时才写入,手工编辑的实现在重新生成时不会被覆盖。 **目录结构:** ``` MiddlewarePath/ ├── auth_middleware.go // type AuthMiddleware struct{} └── role_middleware.go // type RoleMiddleware struct{} ``` **脚手架文件示例:** ```go package middleware import xgocontext "gitee.com/xgo-core/context" // AuthMiddleware handles the "auth" middleware. type AuthMiddleware struct{} // Handle executes the "auth" middleware logic. func (m *AuthMiddleware) Handle(ctx *xgocontext.XGoContext, param string) error { panic("not implemented") // TODO: Implement } ``` ### 7.3 Controller 脚手架(`ControllerPath`) 设置 `ControllerPath` 且 service 上带有 `` 或 `` 注解时,pbgenerator 会在对应子目录下为每个 service 生成一个 controller 文件。 - **文件不存在时** — 生成完整脚手架(struct + 全部 RPC 方法桩)。 - **文件已存在时** — 仅追加尚未声明的 RPC 方法,现有内容(包括手工编写的逻辑)不会被修改。 **目录结构:** ``` ControllerPath/ ├── http/ │ └── my_service.go // MyServiceController struct + HTTP handler 方法 └── grpc/ └── my_service.go // MyServiceController struct + gRPC handler 方法 ``` 生成的文件示例见 [§8.1.9](#819-http--http-controller-生成) 和 [§8.1.10](#8110-grpc--grpc-controller-生成)。 ### 7.4 Container 自动加载(`AutoloadPath`) 设置 `AutoloadPath` 后,pbgenerator 会生成自动加载文件,在 `init()` 中把生成对象注入到 `gitee.com/xgo-core/container` 的默认容器。 生成文件: ``` AutoloadPath/ ├── app_http_controller.go // 注入 ControllerPath/http 中的 controller ├── app_grpc_controller.go // 注入 ControllerPath/grpc 中的 controller ├── app_grpc_client.go // 注入生成的 gRPC client 和 GRPCClient 包装器 ├── app_service.go // 注入 ServicePath 中的 service ├── app_middleware.go // 注入 MiddlewarePath 中的 middleware └── app_route.go // 注入 RoutePath 中的 Router ``` 生成文件名会带上 snake_case 格式的 `AppName` 前缀;每次生成前,pbgenerator 会先删除 `AutoloadPath` 下相同 app 前缀的旧 `.go` 文件。生成代码中的应用包 import 一律使用别名。别名格式为 `AppName + DirectoryType`,service 包则使用 `AppName + ServiceName`;例如 `AppName: "app"` 时,会生成 `AppHTTPController`、`AppGRPCController`、`AppMiddleware`、`AppRoute`,以及类似 `AppUserService` 的 service alias。对于每个 protobuf service,`app_grpc_client.go` 会注入 `&pb.GRPCClient{}`;包装器的 `NewClient() any` 方法会使用注入的连接创建具体的 `pb.NewClient` 实例。 生成的 `app_http_controller.go` 示例: ```go package autoload import ( AppHTTPController "your/module/app/controller/http" "gitee.com/xgo-core/container" ) func init() { container.MustInject(&AppHTTPController.MyServiceController{}) } ``` 生成的 `app_grpc_client.go` 示例: ```go package autoload import ( pb "your/module/gen/mypackage" "gitee.com/xgo-core/container" ) func init() { container.MustInject(&pb.MyServiceGRPCClient{}) } ``` 启用 `app` 注解分组并设置 `AutoloadPath` 后,会自动生成 gRPC client 自动注入文件。每个 protobuf service 都会生成对应的 `GRPCClient` 包装器注入,与 service 是否带有 `` 或 `` 注解无关。容器向包装器注入 `grpc.ClientConnInterface` 后,包装器的 `NewClient() any` 方法会调用 `pb.NewClient` 创建实际 client。使用多个 protobuf 包时,生成文件会为每个包分配唯一的 import alias。 ## 8. Proto 注解 注解写在字段或类型的注释中,使用尖括号语法: ``` // 标志型注解 // 单值注解 // 多值注解 ``` 同一行注释中可以出现多个注解: ```proto string message = 1; // ``` ### 8.1 内置注解 #### 8.1.1 `` — 枚举作为错误类型 标注在枚举上,生成 `Error() string` 方法,使其实现 `error` 接口。可用 `` 自定义各枚举值的错误信息。 ```proto // enum MyEnum { UNKNOWN = 0; // NOT_FOUND = 1; // } ``` 生成: ```go func (e MyEnum) Error() string { ... } ``` #### 8.1.2 `` — 枚举值自定义字符串 标注在枚举值上,控制 `String()` 的输出(若枚举同时带有 ``,也会影响 `Error()`)。 ```proto enum Status { ACTIVE = 0; // INACTIVE = 1; // } ``` 生成: ```go func (e Status) String() string { ... } ``` #### 8.1.3 `` — 覆盖字段 Go 类型 替换 protobuf 生成的字段 Go 类型,并同步更新对应的 getter 方法。 ```proto message HelloReply { string message = 1; // } ``` `.pb.go` 中的结果: ```go type HelloReply struct { Message map[string][]string `protobuf:"..." json:"message"` } func (x *HelloReply) GetMessage() map[string][]string { ... } ``` #### 8.1.4 `` — 为字段开启 omitempty 为标注字段的 `json`、`xml`、`form`、`uri` tag 追加 `,omitempty`。未标注的字段在 tag 注入阶段会全局移除 `omitempty`。 ```proto message HelloReply { string message = 1; // bool success = 2; } ``` `.pb.go` 中的结果: ```go Message string `protobuf:"..." json:"message,omitempty" xml:"message,omitempty" form:"message,omitempty" uri:"message,omitempty"` Success bool `protobuf:"..." json:"success" xml:"success" form:"success" uri:"success"` ``` #### 8.1.5 `` — 自定义 struct tag 字段名 用注解值替换 `json`、`xml`、`form`、`uri` tag 中的字段名,已有的选项(如 `,omitempty`)保持不变。 ```proto message HelloReply { string message = 1; // } ``` `.pb.go` 中的结果: ```go Message string `protobuf:"..." json:"msg" xml:"msg" form:"msg" uri:"msg"` ``` 可与 `` 组合使用: ```proto string message = 1; // // → json:"msg,omitempty" xml:"msg,omitempty" form:"msg,omitempty" uri:"msg,omitempty" ``` #### 8.1.6 `` — 字段校验规则 为标注字段追加 `binding` struct tag。注解中多个规则以冒号分隔,生成时用逗号连接。 ```proto message LoginRequest { string username = 1; // string password = 2; // } ``` `.pb.go` 中的结果: ```go Username string `protobuf:"..." json:"username" ... binding:"required"` Password string `protobuf:"..." json:"password" ... binding:"required,min=6,max=32"` ``` #### 8.1.7 `` — gin 路由生成 在 `RoutePath` 中生成 gin 路由配置。同一个注解用于 **service** 和 **rpc** 两个层级,参数格式不同: | 标注位置 | 格式 | 效果 | |---|---|---| | service | `` | 设置路由分组前缀 | | rpc | `` | 设置路径,HTTP method 默认为 `POST` | | rpc | `` | 显式指定 HTTP method 和路径 | 生成文件集中输出到 `RoutePath`: - **`route.go`** — `Router`,包含 `RegisterHTTPRoutes` 和/或 `RegisterGRPCRoutes` - **`controller.go`** — 聚合的 `HTTPController`、`GRPCController` struct,直接引用 `ControllerPath` 下的 controller - **`middleware.go`** — 存在 `` 注解时生成 ```proto // service MyService { rpc CreateUser(CreateUserRequest) returns (CreateUserReply); // rpc GetUser(GetUserRequest) returns (GetUserReply); // } ``` 生成的 `route.go`: ```go type Router struct { HTTPController HTTPController InvokeController func(*gin.Context, HTTPControllerFunc) } func (rt *Router) RegisterHTTPRoutes(r gin.IRouter) { MyServiceGroup := r.Group("/my-service") MyServiceGroup.POST("/users", rt.httpControllerHandlerFunc(rt.HTTPController.MyServiceHTTPController.CreateUser)) MyServiceGroup.GET("/users", rt.httpControllerHandlerFunc(rt.HTTPController.MyServiceHTTPController.GetUser)) } ``` 生成的 `controller.go`: ```go type HTTPController struct { MyServiceHTTPController *http.MyServiceController } ``` 当 service 标注 `` 时,`controller.go` 还会包含 `GRPCController` struct,`route.go` 会包含 `RegisterGRPCRoutes`。 #### 8.1.8 `` — gin 中间件 在 service 分组或单个 RPC 路由上附加命名中间件。`param` 参数可选;`` 会向 middleware 传入空字符串。`RoutePath/middleware.go` 会聚合 `MiddlewarePath` 中的具体 middleware 实现(详见[§7.2](#72-middleware-脚手架middlewarepath))。 | 标注位置 | 效果 | |---|---| | service | 加入 `r.Group(...)` — 对该 service 下所有 RPC 生效 | | rpc | 仅加入当前路由的处理器链 | ```proto // service MyService { rpc CreateUser(CreateUserRequest) returns (CreateUserReply); // rpc DeleteUser(DeleteUserRequest) returns (DeleteUserReply); // } ``` 生成的 `middleware.go`: ```go type Middleware struct { AuthMiddleware *middleware.AuthMiddleware RoleMiddleware *middleware.RoleMiddleware } ``` 生成的 `route.go`: ```go type Router struct { HTTPController HTTPController InvokeController func(*gin.Context, HTTPControllerFunc) Middleware Middleware InvokeMiddleware func(*gin.Context, HTTPMiddlewareFunc, string) } func (rt *Router) RegisterHTTPRoutes(r gin.IRouter) { MyServiceGroup := r.Group("/my-service", rt.middlewareHandlerFunc(rt.Middleware.AuthMiddleware.Handle, "required")) MyServiceGroup.POST("/users", rt.httpControllerHandlerFunc(rt.HTTPController.MyServiceHTTPController.CreateUser)) MyServiceGroup.DELETE("/users", rt.middlewareHandlerFunc(rt.Middleware.RoleMiddleware.Handle, "admin"), rt.httpControllerHandlerFunc(rt.HTTPController.MyServiceHTTPController.DeleteUser)) } ``` #### 8.1.9 `` — HTTP controller 生成 标注在 **service** 上,在 `ControllerPath/http/` 中生成 HTTP controller 文件。需设置 `ControllerPath`。HTTP controller 使用 [`gitee.com/xgo-core/context`](https://gitee.com/xgo-core/context) 的 `*xgocontext.XGoContext` 作为请求上下文。若文件已存在,只追加缺少的 RPC 方法。 ```proto // service MyService { rpc CreateUser(CreateUserRequest) returns (CreateUserReply); rpc GetUser(GetUserRequest) returns (GetUserReply); } ``` 生成的 `ControllerPath/http/my_service_controller.go`: ```go package http import ( xgocontext "gitee.com/xgo-core/context" "github.com/gin-gonic/gin" pb "your/module/gen/mypackage" myservice "your/module/service/my_service" ) type MyServiceController struct { MyService *myservice.MyService } func (c *MyServiceController) CreateUser(ctx *xgocontext.XGoContext) error { var req pb.CreateUserRequest ginCtx, err := xgocontext.GetParentContext[*gin.Context](ctx) if err != nil { return err } if err := ginCtx.ShouldBind(&req); err != nil { return err } _, err = c.MyService.CreateUser(ctx, &req) return err } ``` #### 8.1.10 `` — gRPC controller 生成 标注在 **service** 上,在 `ControllerPath/grpc/` 中生成 gRPC controller 文件。需设置 `ControllerPath`。若文件已存在,只追加缺少的 RPC 方法。`` 和 `` 可同时标注在同一个 service 上。 ```proto // service MyService { rpc CreateUser(CreateUserRequest) returns (CreateUserReply); } ``` 生成的 `ControllerPath/grpc/my_service.go`: ```go package grpc import ( "context" pb "your/module/gen/mypackage" myservice "your/module/service/my_service" ) type MyServiceController struct { pb.UnimplementedMyServiceServer MyService *myservice.MyService } func (c *MyServiceController) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (rsp *pb.CreateUserReply, err error) { return c.MyService.CreateUser(ctx, req) } ``` #### 8.1.11 `` 与 `` — OpenAPI 文档 设置 `DocPath` 且在 `Annotations` 中选中 `doc` 分组后,任何带 `` 注解的 service 都会在以下位置生成一份包含该 service 全部 RPC 路径的 OpenAPI 3.0.3 JSON 文档: ``` //.json ``` `` 标注在 **RPC** 上,用于设置 OpenAPI 的接口名称(`summary`);未设置时默认使用 RPC 名称。 `` 可标注在 **service** 或 **RPC** 上,用于声明文档中的 HTTP Header: - Header 类型固定为 `string`,且默认必传(`required: true`)。 - service 级 Header 自动继承到该 service 的所有 RPC。 - RPC 级 Header 只作用于当前 RPC;同名 Header 会覆盖 service 级定义。 - `说明` 会写入 OpenAPI 参数的 `description`;说明中包含英文冒号时会完整保留。 - GET 请求的 request message 字段会生成 `in: query` 参数(HTTP 表单/查询参数),不会生成 JSON request body;其它请求方法仍使用 JSON request body。 - 字段上的 `` 会覆盖 OpenAPI schema 的原始 proto 类型;字段 `` 写入展示字段名(`title`),`` 写入字段或参数的 `description`。普通字段注释不会进入接口文档。 ```proto // service UserService { // 查询用户资料。 // rpc GetUser(GetUserRequest) returns (GetUserReply); } ``` 上述 `GetUser` 文档包含 `X-App-Id` 和 `Authorization` 两个必传字符串 Header,接口名称为“查询用户”。 ### 8.2 注解速查表 | 注解 | 作用目标 | 说明 | |---|---|---| | `` | enum | 生成 `Error() string`,实现 `error` 接口 | | `` | enum value | 自定义 `String()` / `Error()` 的输出字符串 | | `` | field | 覆盖生成的 Go 类型并更新 getter | | `` | field | 为字段的 json/xml/form/uri tag 添加 omitempty | | `` | field | 替换 json/xml/form/uri tag 中的字段名 | | `` | field | 追加 `binding` tag,值为校验规则 | | `` | generated gRPC package | 生成或更新 `grpc_client_gen.go`,包含连接字段和 `NewClient() any`;属于 `base` 分组 | | `` | service | 设置路由分组前缀 | | `` | rpc | 设置 HTTP method(默认 `POST`)和路径 | | `` | service / rpc | 向分组或路由附加命名 gin 中间件;`param` 可选 | | `` | service | 在 `ControllerPath/http/` 生成 HTTP controller | | `` | service | 在 `ControllerPath/grpc/` 生成 gRPC controller | | `` | rpc / field | 设置 OpenAPI 接口名称或字段展示名;需启用 `doc` 分组 | | `` | field | 设置 OpenAPI 字段或参数描述;需启用 `doc` 分组 | | `` | service / rpc | 声明 OpenAPI 必传字符串 Header;需启用 `doc` 分组 | ## 9. 扩展自定义注解 实现 `annotation.Handler` 接口,补充 `AnnotationTypes` 供调度器选择,并在 `init()` 函数中调用 `annotation.Register`: ```go package myannotations import "gitee.com/xgo-core/proto-generator/annotation" func init() { annotation.Register(myHandler{}) } type myHandler struct{} func (myHandler) Annotation() string { return "mytag" } func (myHandler) AnnotationTypes() []string { return []string{"base"} } func (myHandler) Generate( doc *annotation.ProtoDoc, param annotation.Param, collector *annotation.FileCollector, pb *annotation.PbFileStore, ) error { for _, file := range doc.Files { for _, msg := range file.Messages { for _, field := range msg.Fields { if annotation.ParseAnnotations(field.Description).Has("mytag") { // 通过 collector 添加生成代码,或通过 pb 修改 .pb.go AST } } } } return nil } ``` `AnnotationTypes` 声明哪些 `GeneratorParam.Annotations` 分组会启用该 handler。可以使用已有分组(`base`、`app` 或 `doc`),也可以定义自有分组名并通过 `Annotations` 传入。 然后在生成器入口处以副作用方式导入该包: ```go import _ "path/to/myannotations" ``` **`FileCollector`** 收集各 handler 生成的代码片段,将同一 enum/类型的多个 handler 输出合并到单个 `*_gen.go` 文件。 **`PbFileStore`** 提供对所有预加载 `.pb.go` AST 的内存访问,全部处理完毕后统一写回磁盘。`ApplyRename(name)` 方法可查询预处理阶段修改过的标识符名称。 ## 10. 运行测试 ```bash go test ./... ``` 依赖 `protoc` / `protoc-gen-go` 的测试在工具未安装时会自动跳过。 ## 11. 许可证 MIT