Files
ginframework/http/openapi.go
T
zhangdeman b4a21f53ac
Verify / verify (push) Canceled after 0s
feat(http): 增加 OpenAPI 契约生成能力
从已注册 Controller 的 Form、返回类型及字段声明生成请求、
响应和校验约束,补充显式安全方案与操作级覆盖。
复用 kin-openapi 原生类型与校验,保留合并绑定语义,
为原生路由和无法等价映射的声明提供补充入口。

同步接入指南、迁移边界和可独立运行的契约导出示例。
验证:make verify、make race-check 及实际示例导出通过。
2026-11-26 21:10:02 -08:00

224 lines
9.9 KiB
Go

package http
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"git.zhangdeman.cn/github/ginframework/http/request"
failure "git.zhangdeman.cn/github/ginframework/internal/failure"
"github.com/getkin/kin-openapi/openapi3"
)
const (
openAPIVersion = "3.0.3"
publicSecurity = "-"
)
// OpenAPIOptions 是一次文档生成的数据及显式扩展点,不参与运行时认证。
type OpenAPIOptions struct {
Title string `json:"title" dc:"必填的 API 文档标题"`
Version string `json:"version" dc:"必填的应用 API 版本,不是 OpenAPI 规范版本"`
Servers openapi3.Servers `json:"servers,omitempty" dc:"可选的部署入口列表"`
SecuritySchemes openapi3.SecuritySchemes `json:"security_schemes,omitempty" dc:"原生安全方案声明,不包含真实凭据"`
Security openapi3.SecurityRequirements `json:"security,omitempty" dc:"默认安全要求;数组为或,同一对象中的多个方案为且"`
Customize func(Metadata, *openapi3.Operation) error `json:"-" dc:"可选的单路由契约补充,处理原生响应、复杂约束或 OAuth scope"`
}
// OpenAPI 从已成功注册的路由生成独立的 OpenAPI 3.0.3 文档。
// 入参:options 为标题、版本、安全声明及可选操作补充函数。
// 返回:已解析引用并通过规范校验的原生文档;声明、类型或补充错误返回 nil 与原因链。
// 副作用:只读取路由快照,不冻结注册、不发布端点、不执行 Controller 或认证中间件。
func (s *Server) OpenAPI(options OpenAPIOptions) (*openapi3.T, error) {
if strings.TrimSpace(options.Title) == "" || strings.TrimSpace(options.Version) == "" {
return nil, failure.Wrap(codeOpenAPIOptions, "validate OpenAPI options failed", errors.New("title and version are required"))
}
s.lock.Lock()
routes := append([]route(nil), s.routes...)
s.lock.Unlock()
// 先复制调用方数据,库的生成和校验不修改应用拥有的安全方案。
doc, err := loadOpenAPI(&openapi3.T{OpenAPI: openAPIVersion, Info: &openapi3.Info{Title: options.Title, Version: options.Version}, Paths: openapi3.NewPaths(), Components: &openapi3.Components{Schemas: openapi3.Schemas{}, SecuritySchemes: options.SecuritySchemes}, Security: options.Security, Servers: options.Servers})
if err != nil {
return nil, failure.Wrap(codeOpenAPICopy, "copy OpenAPI options failed", err)
}
if doc.Components == nil {
doc.Components = &openapi3.Components{}
}
doc.Components.Schemas = openapi3.Schemas{}
for _, item := range routes {
path, parameters, pathErr := openAPIPath(item.meta.Path)
if pathErr != nil {
return nil, failure.Wrap(codeOpenAPIPath, "convert OpenAPI route path failed", pathErr)
}
if !strings.Contains(" GET PUT POST DELETE OPTIONS HEAD PATCH TRACE ", " "+item.meta.Method+" ") {
return nil, failure.Wrap(codeOpenAPIMethod, "convert OpenAPI route method failed", errors.New("method has no OpenAPI 3.0 operation"))
}
operation, operationErr := s.openAPIOperation(item, doc.Components.Schemas, parameters)
if operationErr != nil {
return nil, operationErr
}
if item.security != "" {
requirements := openapi3.SecurityRequirements{}
if item.security != publicSecurity {
requirement := openapi3.SecurityRequirement{}
for _, name := range strings.Split(item.security, ",") {
name = strings.TrimSpace(name)
if name == "" {
return nil, failure.Wrap(codeOpenAPISecurity, "validate route security declaration failed", errors.New("empty security scheme name"))
}
requirement[name] = []string{}
}
requirements = append(requirements, requirement)
}
operation.Security = &requirements
}
if options.Customize != nil {
if err = options.Customize(item.meta, operation); err != nil {
return nil, failure.Wrap(codeOpenAPICustomize, "customize OpenAPI operation failed", err)
}
}
entry := doc.Paths.Value(path)
if entry == nil {
entry = &openapi3.PathItem{}
doc.Paths.Set(path, entry)
}
if entry.GetOperation(item.meta.Method) != nil {
return nil, failure.Wrap(codeOpenAPIDuplicate, "validate OpenAPI route uniqueness failed", errors.New("multiple Gin routes normalize to one operation"))
}
entry.SetOperation(item.meta.Method, operation)
}
// 经过序列化边界重新解析引用,也验证应用补充后的真实输出。
doc, err = loadOpenAPI(doc)
if err == nil {
err = failure.Wrap(codeOpenAPISecurity, "validate OpenAPI security references failed", validateSecurity(doc))
}
if err == nil {
err = doc.Validate(context.Background())
}
if err != nil {
return nil, failure.Wrap(codeOpenAPIValidate, "validate generated OpenAPI document failed", err)
}
return doc, nil
}
// loadOpenAPI 通过原生加载器复制文档并解析内部引用,禁止加载外部引用。
// 入参:doc 为尚未对外发布的文档;返回独立对象或序列化/引用错误。
func loadOpenAPI(doc *openapi3.T) (*openapi3.T, error) {
raw, err := json.Marshal(doc)
if err != nil {
return nil, err
}
return openapi3.NewLoader().LoadFromData(raw)
}
// openAPIOperation 根据普通路由的静态签名生成参数及协议响应。
// 入参:item 为注册快照,schemas 为本次组件集合,paths 为路径占位参数。
// 返回:原生路由仅返回明确的未推断标记,供应用显式补充。
func (s *Server) openAPIOperation(item route, schemas openapi3.Schemas, paths openapi3.Parameters) (*openapi3.Operation, error) {
op := &openapi3.Operation{Summary: item.meta.Summary, Parameters: paths, Responses: openapi3.NewResponses()}
if item.meta.Tag != "" {
op.Tags = []string{item.meta.Tag}
}
if item.input == nil {
op.Extensions = map[string]any{"x-gin-native": true}
op.Responses.Set("default", &openapi3.ResponseRef{Value: openapi3.NewResponse().WithDescription("Native handler response; application contract required")})
return op, nil
}
if err := s.openAPIRequest(op, item, schemas); err != nil {
return nil, failure.Wrap(codeOpenAPISchema, "generate OpenAPI request schema failed", err)
}
output, err := responseContractSchema(item.output, schemas)
if err != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI response schema failed", err)
}
envelope, err := responseContractSchema(reflect.TypeOf(Envelope{}), schemas)
if err != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI envelope schema failed", err)
}
envelope.Value.Properties["data"] = output
envelope.Value.Required = []string{"code", "message", "data", "trace_id", "cost_ms"}
envelope.Value.Properties["code"].Value.Enum = []any{s.config.SuccessCode}
op.Responses.Set("200", jsonContract("Successful response", envelope))
for _, status := range []int{400, 413, 415, 500, 504} {
errorEnvelope, schemaErr := responseContractSchema(reflect.TypeOf(Envelope{}), schemas)
if schemaErr != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI error schema failed", schemaErr)
}
if status == 400 {
details, detailErr := responseContractSchema(reflect.TypeOf(request.ValidationDetails{}), schemas)
if detailErr != nil {
return nil, failure.Wrap(codeOpenAPIResponse, "generate OpenAPI validation schema failed", detailErr)
}
details.Value.Nullable = true
errorEnvelope.Value.Properties["data"] = details
}
op.Responses.Set(fmt.Sprint(status), jsonContract(http.StatusText(status), errorEnvelope))
}
if item.meta.Method == http.MethodHead {
for _, response := range op.Responses.Map() {
response.Value.Content = nil
}
}
return op, nil
}
// jsonContract 构造 JSON 响应声明;入参为安全描述和结构引用,返回原生响应。
func jsonContract(description string, schema *openapi3.SchemaRef) *openapi3.ResponseRef {
return &openapi3.ResponseRef{Value: openapi3.NewResponse().WithDescription(description).WithContent(openapi3.Content{"application/json": &openapi3.MediaType{Schema: schema}})}
}
// openAPIPath 转换 Gin 占位符并保留 catch-all 的扩展声明。
// 入参:path 为最终路径;返回规范路径、必填字符串占位参数或不支持的路径错误。
func openAPIPath(path string) (string, openapi3.Parameters, error) {
parts := strings.Split(path, "/")
parameters := openapi3.Parameters{}
for index, part := range parts {
if strings.HasPrefix(part, ":") || strings.HasPrefix(part, "*") {
name := part[1:]
if name == "" || strings.ContainsAny(name, "{}") {
return "", nil, errors.New("invalid Gin path parameter")
}
parameter := openapi3.NewPathParameter(name).WithSchema(openapi3.NewStringSchema())
if part[0] == '*' {
parameter.Extensions = map[string]any{"x-gin-catch-all": true}
}
parameters = append(parameters, &openapi3.ParameterRef{Value: parameter})
parts[index] = "{" + name + "}"
} else if strings.ContainsAny(part, ":*{}") {
return "", nil, errors.New("embedded path parameters need an application contract")
}
}
return strings.Join(parts, "/"), parameters, nil
}
// validateSecurity 拒绝拼错或缺失的方案引用,防止文档出现无定义认证要求。
// 入参:doc 为完整文档;返回不存在的方案或非 OAuth scope 声明错误。
func validateSecurity(doc *openapi3.T) error {
all := []openapi3.SecurityRequirements{doc.Security}
for _, path := range doc.Paths.Map() {
for _, op := range path.Operations() {
if op.Security != nil {
all = append(all, *op.Security)
}
}
}
for _, requirements := range all {
for _, requirement := range requirements {
for name, scopes := range requirement {
scheme := doc.Components.SecuritySchemes[name]
if scheme == nil || scheme.Value == nil {
return fmt.Errorf("undefined security scheme %q", name)
}
if len(scopes) != 0 && scheme.Value.Type != "oauth2" && scheme.Value.Type != "openIdConnect" {
return errors.New("scopes require OAuth2 or OpenID Connect")
}
}
}
}
return nil
}