proto

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package proto provides proto generator implementation. This file implements typed RPC client wrapper generation from proto files.

Proto 包提供 proto 生成器实现。 本文件实现从 proto 文件生成类型化 RPC 客户端 wrapper。

Package proto provides enum parser for converting Go const/iota to proto enum. Supports iota expression evaluation and enum name inference. Generates proto enum definitions from Go source code.

Proto 包提供枚举解析器,用于将 Go const/iota 转换为 proto enum。 支持 iota 表达式求值和枚举名推断。 从 Go 源代码生成 proto enum 定义。

Package proto provides proto generator implementation. Core implementation of ProtoGenerator contract. Supports protoc invocation and Go AST parsing.

Proto 包提供 proto 生成器实现。 ProtoGenerator 契约的核心实现。 支持 protoc 调用和 Go AST 解析。

Package proto provides handler parser for Gin HTTP handlers. Extracts request/response types from Gin handler functions. Supports ShouldBind/JSON response type inference.

Proto 包提供 Handler 解析器,用于 Gin HTTP handlers。 从 Gin handler 函数提取请求/响应类型。 支持 ShouldBind/JSON 响应类型推断。

Package proto provides OpenAPI documentation generator implementation. This file implements OpenAPI 3.0 spec generation from proto files. Parses google.api.http annotations and generates REST API documentation.

Proto 包提供 OpenAPI 文档生成器实现。 本文件实现从 proto 文件生成 OpenAPI 3.0 规范。 解析 google.api.http 注解并生成 REST API 文档。

Package proto provides OpenAPI Schema generation from proto messages. This file implements proto message parsing and schema conversion. Supports nested messages, repeated fields, enums, and special types.

Proto 包提供从 proto message 生成 OpenAPI Schema 的实现。 本文件实现 proto message 解析和 schema 转换。 支持嵌套消息、repeated 字段、枚举和特殊类型。

Package proto provides proto generator service for gorp framework. Supports two workflows: Proto-first and Service-first. Generates Go code from proto, or proto from Go service interface.

Proto 包提供 proto 生成器服务,用于 gorp 框架。 支持两种工作流:Proto-first 和 Service-first。 从 proto 生成 Go 代码,或从 Go service 接口生成 proto。

Package proto provides route parser for Gin routes. Converts Gin route definitions to proto service definitions. Supports path parameter conversion (:id -> {id}).

Proto 包提供路由解析器,用于 Gin 路由。 将 Gin 路由定义转换为 proto service 定义。 支持路径参数转换(:id -> {id})。

Package proto provides proto generator implementation. This file implements service skeleton generation from proto files. Generates HTTP handler, gRPC service implementation and route registration.

Proto 包提供 proto 生成器实现。 本文件实现从 proto 文件生成服务骨架代码。 生成 HTTP handler、gRPC service 实现和路由注册。

Package proto provides type resolver for cross-file/cross-package type resolution. Parses Go AST to resolve type dependencies across imports. Caches resolved types for performance.

Proto 包提供类型解析器,用于跨文件/跨包类型解析。 解析 Go AST 以解决跨 import 的类型依赖。 缓存已解析的类型以提高性能。

Package proto provides validation rule converter. Converts Go validate/binding tags to protoc-gen-validate annotations. Supports common validation rules: required, min, max, email, etc.

Proto 包提供验证规则转换器。 将 Go validate/binding tag 转换为 protoc-gen-validate 注解。 支持常见验证规则:required、min、max、email 等。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DetectEnumType

func DetectEnumType(typeName string, enums []EnumInfo) string

DetectEnumType 检测字段类型是否是枚举类型。

中文说明: - 根据已解析的枚举列表检测类型; - 返回枚举类型名或空字符串。

func ExtractPathParams

func ExtractPathParams(path string) []string

ExtractPathParams 从路径中提取路径参数。

中文说明: - 解析 Gin 路径参数格式(如 /users/:id); - 返回参数名列表。

func FindGoFileInDir

func FindGoFileInDir(dir, typeName string) (string, error)

FindGoFileInDir 在目录中查找包含指定类型的 Go 文件。

中文说明: - 遍历目录下的 Go 文件; - 查找包含指定类型定义的文件。

func GenerateProtoEnum

func GenerateProtoEnum(enum EnumInfo) string

GenerateProtoEnum 生成 proto enum 定义。

中文说明: - 根据枚举信息生成 proto enum 语法; - 包含枚举值和注释。

func GenerateProtoValidation

func GenerateProtoValidation(fieldType string, rules []integrationcontract.ValidationRule) string

GenerateProtoValidation 生成 proto 验证注解。

中文说明: - 根据验证规则生成 protoc-gen-validate 格式的注解; - 例如:`[(validate.rules).string.min_len = 6]`。

func GenerateRequestMessageFromHandler

func GenerateRequestMessageFromHandler(handlerName string, pathParams []string, requestType *integrationcontract.TypeDef) string

GenerateRequestMessageFromHandler 根据 Handler 信息生成请求消息。

中文说明: - 从路径参数和 Handler 分析结果生成请求 message; - 包含路径参数和请求体字段。

Types

type EnumInfo

type EnumInfo struct {
	// TypeName 枚举类型名称
	TypeName string

	// Values 枚举值列表
	Values []integrationcontract.EnumValue

	// Comments 注释
	Comments []string
}

EnumInfo 枚举信息。

type EnumParser

type EnumParser struct {
	// contains filtered or unexported fields
}

EnumParser 枚举类型解析器。

中文说明: - 解析 Go 的 const/iota 枚举定义; - 支持识别枚举类型和值; - 生成 proto enum 定义。

func NewEnumParser

func NewEnumParser() *EnumParser

NewEnumParser 创建枚举解析器。

func (*EnumParser) ParseAST

func (p *EnumParser) ParseAST(f *ast.File) []EnumInfo

ParseAST 从 AST 解析枚举定义。

func (*EnumParser) ParseFile

func (p *EnumParser) ParseFile(filePath string) ([]EnumInfo, error)

ParseFile 解析文件中的枚举定义。

中文说明: - 解析 Go 文件中的 const 块; - 识别 iota 枚举模式; - 返回枚举信息列表。

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator 实现 ProtoGenerator 接口。

中文说明: - 支持两种工作流:Proto-first 和 Service-first; - Proto-first:调用 protoc 生成 Go 代码; - Service-first:解析 Go AST 生成 Proto。

func NewGenerator

NewGenerator 创建 Generator。

func (*Generator) GenClient

GenClient generates typed RPC client wrapper from proto file. Parses the proto file to extract service and method definitions, then generates a Go file with typed client struct and methods.

GenClient 从 proto 文件生成类型化 RPC 客户端 wrapper。 解析 proto 文件提取服务和方法的定义, 然后生成包含类型化客户端 struct 和方法的 Go 文件。

func (*Generator) GenFromProto

GenFromProto 从 proto 文件生成 Go 代码(标准 protoc 流程)。

中文说明: - 调用 protoc 命令生成 Go 代码; - 支持 --go_out 和 --go-grpc_out; - 可选支持 --grpc-gateway_out(IncludeHTTP)。

func (*Generator) GenFromRoute

GenFromRoute 从 Gin 路由生成 proto 文件(迁移工具)。

中文说明: - 用于将现有 Gin 项目迁移到 gRPC/proto 工作流; - 解析 Gin 路由定义,推断请求/响应类型; - 自动添加 HTTP 注解。

func (*Generator) GenFromService

GenFromService 从 Go Service 接口反向生成 proto 文件。

中文说明: - 解析 Go AST 提取接口定义; - 自动扫描同 package 下全部非测试 Go 文件,收集完整 struct 定义; - 对 request/response 可达的自定义类型构建递归闭包; - 对无法解析的自定义类型直接报错,而不是生成 placeholder。

func (*Generator) GenOpenAPI

GenOpenAPI generates OpenAPI/Swagger documentation from proto file. Parses proto annotations (google.api.http) and generates OpenAPI 3.0 spec.

GenOpenAPI 从 proto 文件生成 OpenAPI/Swagger 文档。 解析 proto 注解 (google.api.http) 并生成 OpenAPI 3.0 规范。

func (*Generator) GenService

GenService generates HTTP handler, gRPC service skeleton and route registration from proto file. Enables proto-first workflow: proto → service implementation skeleton.

GenService 从 proto 文件生成 HTTP handler、gRPC service skeleton 和路由注册。 支持闭环 proto-first 工作流:proto → 服务实现骨架。

func (*Generator) GetConfig

GetConfig 获取当前配置。

type HandlerParser

type HandlerParser struct {
	// contains filtered or unexported fields
}

HandlerParser Handler 解析器。

中文说明: - 解析 Gin Handler 函数定义; - 提取请求/响应类型信息; - 支持从 Handler 所在文件解析相关类型。

func NewHandlerParser

func NewHandlerParser() *HandlerParser

NewHandlerParser 创建 Handler 解析器。

func (*HandlerParser) InferRequestTypeFromHandler

func (p *HandlerParser) InferRequestTypeFromHandler(fnDecl *ast.FuncDecl, structDefs map[string][]integrationcontract.FieldDef) *integrationcontract.TypeDef

InferRequestTypeFromHandler 从 Handler 函数推断请求类型。

中文说明: - 分析 Handler 函数体; - 查找 ShouldBindJSON 等调用; - 提取绑定的结构体类型。

func (*HandlerParser) ParseHandlerFile

func (p *HandlerParser) ParseHandlerFile(filePath string) (map[string]*HandlerTypeInfo, error)

ParseHandlerFile 解析 Handler 文件,提取所有 Handler 的类型信息。

中文说明: - 解析指定文件中的所有 Handler 函数; - 返回 Handler 名称到类型信息的映射。

func (*HandlerParser) ParseHandlers

func (p *HandlerParser) ParseHandlers(filePath string, handlerNames []string) (map[string]*HandlerTypeInfo, error)

ParseHandlers 解析指定的 Handler 函数列表。

中文说明: - 解析指定文件中的特定 Handler 函数; - 只返回指定的 Handler 类型信息。

type HandlerTypeInfo

type HandlerTypeInfo struct {
	// HandlerName Handler 函数名
	HandlerName string

	// RequestType 请求类型
	RequestType *integrationcontract.TypeDef

	// ResponseType 响应类型
	ResponseType *integrationcontract.TypeDef

	// RequestTypeName 请求类型名称
	RequestTypeName string

	// ResponseTypeName 响应类型名称
	ResponseTypeName string
}

HandlerTypeInfo Handler 类型信息。

type Media

type Media struct {
	Schema Schema `json:"schema" yaml:"schema"`
}

Media represents OpenAPI media type.

type OpenAPIComponents

type OpenAPIComponents struct {
	Schemas         map[string]Schema         `json:"schemas,omitempty" yaml:"schemas,omitempty"`
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"`
}

OpenAPIComponents represents OpenAPI components section.

type OpenAPIDoc

type OpenAPIDoc struct {
	OpenAPI    string              `json:"openapi" yaml:"openapi"`
	Info       OpenAPIInfo         `json:"info" yaml:"info"`
	Servers    []OpenAPIServer     `json:"servers,omitempty" yaml:"servers,omitempty"`
	Paths      map[string]PathItem `json:"paths" yaml:"paths"`
	Components OpenAPIComponents   `json:"components,omitempty" yaml:"components,omitempty"`
}

OpenAPIDoc represents OpenAPI 3.0 document structure.

type OpenAPIInfo

type OpenAPIInfo struct {
	Title       string `json:"title" yaml:"title"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	Version     string `json:"version" yaml:"version"`
}

OpenAPIInfo represents OpenAPI info section.

type OpenAPIServer

type OpenAPIServer struct {
	URL         string `json:"url" yaml:"url"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
}

OpenAPIServer represents OpenAPI server section.

type Operation

type Operation struct {
	Summary     string                `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description string                `json:"description,omitempty" yaml:"description,omitempty"`
	OperationID string                `json:"operationId" yaml:"operationId"`
	Tags        []string              `json:"tags,omitempty" yaml:"tags,omitempty"`
	Parameters  []Parameter           `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	RequestBody *RequestBody          `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`
	Responses   map[string]Response   `json:"responses" yaml:"responses"`
	Security    []map[string][]string `json:"security,omitempty" yaml:"security,omitempty"`
}

Operation represents OpenAPI operation.

type Parameter

type Parameter struct {
	Name        string `json:"name" yaml:"name"`
	In          string `json:"in" yaml:"in"`
	Required    bool   `json:"required,omitempty" yaml:"required,omitempty"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	Schema      Schema `json:"schema" yaml:"schema"`
}

Parameter represents OpenAPI parameter.

type PathItem

type PathItem struct {
	Get     *Operation `json:"get,omitempty" yaml:"get,omitempty"`
	Post    *Operation `json:"post,omitempty" yaml:"post,omitempty"`
	Put     *Operation `json:"put,omitempty" yaml:"put,omitempty"`
	Delete  *Operation `json:"delete,omitempty" yaml:"delete,omitempty"`
	Patch   *Operation `json:"patch,omitempty" yaml:"patch,omitempty"`
	Summary string     `json:"summary,omitempty" yaml:"summary,omitempty"`
}

PathItem represents OpenAPI path item.

type ProtoEnum

type ProtoEnum struct {
	// Name enum 名称
	Name string

	// Values enum 值列表
	Values []ProtoEnumValue

	// Description 注释描述
	Description string
}

ProtoEnum 表示从 proto 文件解析出的 enum 定义。

中文说明: - 包含 enum 名称和值列表; - 用于生成 OpenAPI enum schema。

type ProtoEnumValue

type ProtoEnumValue struct {
	// Name 值名称
	Name string

	// Number 值编号
	Number int
}

ProtoEnumValue 表示 enum 的一个值。

type ProtoField

type ProtoField struct {
	// Name 字段名
	Name string

	// Type 字段类型(string/int32/bool/MessageName等)
	Type string

	// Number 字段编号
	Number int

	// Repeated 是否是 repeated 字段(数组)
	Repeated bool

	// Optional 是否是 optional 字段
	Optional bool

	// MapKey map 类型的键类型(如果字段是 map)
	MapKey string

	// MapValue map 类型的值类型(如果字段是 map)
	MapValue string

	// Description 注释描述
	Description string
}

ProtoField 表示 proto message 的字段定义。

中文说明: - 包含字段名、类型、编号和修饰符; - 支持 optional/repeated/map 等修饰符。

type ProtoFileContent

type ProtoFileContent struct {
	// Package proto 包名
	Package string

	// Messages message 定义列表
	Messages []ProtoMessage

	// Enums enum 定义列表
	Enums []ProtoEnum

	// Services service 定义列表
	Services []ProtoService
}

ProtoFileContent 表示解析后的 proto 文件内容。

中文说明: - 包含所有 message、enum 和 service 定义; - 用于生成完整的 OpenAPI 文档。

type ProtoMessage

type ProtoMessage struct {
	// Name message 名称
	Name string

	// Fields 字段列表
	Fields []ProtoField

	// Description 注释描述
	Description string
}

ProtoMessage 表示从 proto 文件解析出的 message 定义。

中文说明: - 包含 message 名称和字段列表; - 用于生成 OpenAPI Components Schemas。

type ProtoMethod

type ProtoMethod struct {
	Name         string
	RequestType  string
	ResponseType string
	InputStream  bool
	OutputStream bool
	// HTTP routing info from google.api.http annotation.
	// HTTP 路由信息,从 google.api.http 注解解析。
	HTTPMethod string // GET, POST, PUT, DELETE, PATCH
	HTTPPath   string // /v1/users/{id}
	HTTPBody   string // "*" or field name for body mapping
	// Auth and middleware info from gorp options.
	// 认证和中间件信息,从 gorp 选项解析。
	AuthRequired bool     // 是否要求认证
	AuthRoles    []string // 要求的角色
	AuthSkip     bool     // 跳过认证
	Middleware   []string // 中间件名称列表
	RateLimitRPS int32    // 每秒请求数限制
	RateLimitRPM int32    // 每分钟请求数限制
	RateLimitKey string   // 限流键
}

ProtoMethod describes one method parsed from proto service.

ProtoMethod 描述从 proto 服务解析出的一个方法。

type ProtoService

type ProtoService struct {
	Name    string
	Methods []ProtoMethod
}

ProtoService describes one service parsed from proto file.

ProtoService 描述从 proto 文件解析出的一个服务。

type Provider

type Provider struct{}

Provider registers proto generator service. Core logic: Read proto config, create Generator, bind to container.

Provider 注册 proto 生成器服务。 核心逻辑:读取 proto 配置、创建 Generator、绑定到容器。

func NewProvider

func NewProvider() *Provider

NewProvider creates a new proto generator provider.

NewProvider 创建新的 proto 生成器 provider。

func (*Provider) Boot

Boot initializes the proto generator provider. No additional startup logic required.

Boot 初始化 proto 生成器 provider。 无需额外启动逻辑。

func (*Provider) IsDefer

func (p *Provider) IsDefer() bool

IsDefer indicates proto generator should defer loading. Generator is typically used during build/deployment phase.

IsDefer 表示 proto 生成器应延迟加载。 生成器通常在构建/部署阶段使用。

func (*Provider) Name

func (p *Provider) Name() string

Name returns provider name for identification.

Name 返回 provider 名称,用于标识。

func (*Provider) Provides

func (p *Provider) Provides() []string

Provides returns the capability keys this provider exposes. Exposes ProtoGeneratorKey for proto generation service.

Provides 返回 provider 暴露的能力键。 暴露 ProtoGeneratorKey 用于 proto 生成服务。

func (*Provider) Register

func (p *Provider) Register(c runtimecontract.Container) error

Register binds the proto generator factory to the container. Core logic: Read config, create Generator instance, bind to container.

Register 将 proto 生成器工厂绑定到容器。 核心逻辑:读取配置、创建 Generator 实例、绑定到容器。

type RequestBody

type RequestBody struct {
	Required bool             `json:"required,omitempty" yaml:"required,omitempty"`
	Content  map[string]Media `json:"content" yaml:"content"`
}

RequestBody represents OpenAPI request body.

type Response

type Response struct {
	Description string           `json:"description,omitempty" yaml:"description,omitempty"`
	Content     map[string]Media `json:"content,omitempty" yaml:"content,omitempty"`
}

Response represents OpenAPI response.

type Schema

type Schema struct {
	Type                 string            `json:"type,omitempty" yaml:"type,omitempty"`
	Format               string            `json:"format,omitempty" yaml:"format,omitempty"`
	Properties           map[string]Schema `json:"properties,omitempty" yaml:"properties,omitempty"`
	Ref                  string            `json:"$ref,omitempty" yaml:"$ref,omitempty"`
	Items                *Schema           `json:"items,omitempty" yaml:"items,omitempty"`
	AdditionalProperties *Schema           `json:"additionalProperties,omitempty" yaml:"additionalProperties,omitempty"`
	Enum                 []string          `json:"enum,omitempty" yaml:"enum,omitempty"`
	Description          string            `json:"description,omitempty" yaml:"description,omitempty"`
	Example              interface{}       `json:"example,omitempty" yaml:"example,omitempty"`
	Required             []string          `json:"required,omitempty" yaml:"required,omitempty"`
}

Schema represents OpenAPI schema.

type SecurityScheme

type SecurityScheme struct {
	Type         string `json:"type" yaml:"type"`
	Name         string `json:"name,omitempty" yaml:"name,omitempty"`
	In           string `json:"in,omitempty" yaml:"in,omitempty"`
	Scheme       string `json:"scheme,omitempty" yaml:"scheme,omitempty"`
	BearerFormat string `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"`
}

SecurityScheme represents OpenAPI security scheme.

type TypeResolver

type TypeResolver struct {
	// contains filtered or unexported fields
}

TypeResolver 类型解析器。

中文说明: - 解析跨文件、跨包的类型定义; - 支持递归解析嵌套类型的依赖; - 缓存已解析的目录与文件以提高性能。

func NewTypeResolver

func NewTypeResolver(importPaths []string) *TypeResolver

NewTypeResolver 创建类型解析器。

中文说明: - importPaths 指定 import 的搜索路径; - 用于查找 import 的类型定义目录。

func (*TypeResolver) ResolveAllTypes

func (r *TypeResolver) ResolveAllTypes(mainFile string, initialTypes []string) (map[string]*integrationcontract.TypeDef, error)

ResolveAllTypes 从主文件出发解析所有初始类型的完整递归闭包。

中文说明: - 主文件同包类型由 generator 主链路负责收集; - 这里主要负责 import 引入的外部类型递归补全; - 会根据 TypeDef.Package 优先在对应 import 目录中查找。

func (*TypeResolver) ResolveImports

func (r *TypeResolver) ResolveImports(f *ast.File, baseDir string) map[string]string

ResolveImports 解析文件的 import 语句并返回“代码里使用的包名 -> 对应目录”。

中文说明: - 如果使用 import alias,则用 alias 作为 key; - 否则使用 import path 的最后一个目录名作为包名; - 返回值用于解析 SelectorExpr(如 time.Time / dto.Profile)。

func (*TypeResolver) ResolveType

func (r *TypeResolver) ResolveType(typeName, dir string) (*integrationcontract.TypeDef, []string, error)

ResolveType 解析目录中的单个类型定义。

中文说明: - 目录作为最小缓存单元,先扫描整个目录再取目标类型; - 返回该类型以及它依赖的自定义类型列表。

func (*TypeResolver) ResolveTypesFromImport

func (r *TypeResolver) ResolveTypesFromImport(importPath string, typeNames []string, baseDir string) (map[string]*integrationcontract.TypeDef, error)

ResolveTypesFromImport 从 import 目录解析多个类型定义。

中文说明: - 入参 importPath 可以是 import 路径,也可以直接是目录路径; - 返回目录中命中的类型定义集合。

type ValidationConverter

type ValidationConverter struct {
	// contains filtered or unexported fields
}

ValidationConverter 验证规则转换器。

中文说明: - 将 Go 的 validate/binding tag 转换为 proto 验证规则; - 支持常见的验证规则映射; - 生成 protoc-gen-validate 兼容的注解。

func NewValidationConverter

func NewValidationConverter() *ValidationConverter

NewValidationConverter 创建验证规则转换器。

func (*ValidationConverter) ConvertTag

func (c *ValidationConverter) ConvertTag(tag string, fieldType string) []integrationcontract.ValidationRule

ConvertTag 转换验证 tag 为 proto 验证规则。

中文说明: - 解析 Go struct tag 中的验证规则; - 转换为 proto 验证注解格式; - 支持 binding 和 validate 两种 tag 格式。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL