基础核心能力 #1

Merged
zhangdeman merged 5 commits from codex/initial-framework into master 2026-11-28 15:02:43 +08:00
13 changed files with 1304 additions and 8 deletions
b4a21f53ac feat(http): 增加 OpenAPI 契约生成能力
白茶清欢
2026-11-26 21:10:02 -08:00
Commit 3 of 5
Show all commits

No files matched your search

+8
View File
@@ -30,6 +30,14 @@ go run ./examples/application -config examples/application/config.yml
普通 Controller 默认有 30 秒合作式预算;校验错误提供安全字段提示。健康检查需由应用显式注册并在依赖就绪后置为 ready,详见接入指南。
OpenAPI 契约可直接从 Controller 签名、字段 tag 与显式安全方案生成,不需要启动服务:
```sh
go run ./examples/openapi -out /tmp/ginframework-openapi.json
```
请求/响应 Schema、校验约束、安全声明和原生路由补充方式见接入指南 5.3。安全声明不代替认证中间件,文档端点和 UI 由应用显式发布。
## 开发与验证
先读取 [AGENTS.md](AGENTS.md) 和 [工程技术规约](docs/standards/technical-specification.md)。
+51 -4
View File
@@ -35,12 +35,12 @@ go mod tidy
| `database/sqllog` | GORM 官方 Trace 与 SQL 脱敏 | 自建原生 GORM 的可选日志适配 |
| `redis` | 原生 Redis 客户端创建与探测 | 应用装配根 |
| `redis/commandlog` | 官方 Hook 与 Pipeline 执行观测 | 自建原生 Redis 的可选日志适配 |
| `http` | Gin Server、Form/Meta、响应、可信注入、健康检查、合作式预算与排空 | HTTP 入口 |
| `http` | Gin Server、Form/Meta、响应、可信注入、健康检查、合作式预算、OpenAPI 契约与排空 | HTTP 入口 |
| `http/request` | URI/Query/Body、multipart、正文限制、Context 校验与字段级提示 | 自定义请求适配 |
| `httpclient` | 出站连接池、请求编码、有界响应、原生流式与安全流水 | 第三方服务适配 |
<!-- capabilities:end -->
库不承载业务认证、权限、用户/管理员模型、数据库审计表、缓存 Key、锁、队列和供应商成功码。CORS、请求限流、OpenAPI/Scalar 展示与 pprof 当前没有内置装配能力。
库不承载业务认证、权限、用户/管理员模型、数据库审计表、缓存 Key、锁、队列和供应商成功码。支持 OpenAPI 契约导出;CORS、请求限流、Scalar/Swagger UI 展示与 pprof 当前没有内置装配能力。
## 3. 最小 HTTP 服务
@@ -87,9 +87,9 @@ if err = server.Group("/api", nil, &Example{}); err != nil {
}
```
完整路由为 `GET /api/ping`。Form 的 path 不重复声明入口前缀。支持的 tag 是 `path`、`method`、`summary`、`tag`、`max-body-bytes`、`max-exec-time`;method 可用逗号声明多个方法。Controller 使用指针实例,方法签名为 `func(*gin.Context, Form或*Form) (公开结果, error)`。
完整路由为 `GET /api/ping`。Form 的 path 不重复声明入口前缀。支持的 tag 是 `path`、`method`、`summary`、`tag`、`max-body-bytes`、`max-exec-time`、`security`;method 可用逗号声明多个方法。security 只声明文档安全要求,不执行认证。Controller 使用指针实例,方法签名为 `func(*gin.Context, Form或*Form) (公开结果, error)`。
同一 Group 可一次传多个 Controller;整批检查成功后才提交。`Handler()`、`Serve(listener)` 或 `Shutdown(ctx)` 会冻结后续注册。不能在服务运行中继续添加路由。`Routes()` 返回包含最终完整路径的副本,可交给应用文档生成器。
同一 Group 可一次传多个 Controller;整批检查成功后才提交。`Handler()`、`Serve(listener)` 或 `Shutdown(ctx)` 会冻结后续注册。不能在服务运行中继续添加路由。`Routes()` 保留轻量路径快照;`OpenAPI(options)` 从注册签名生成独立的完整契约,见 5.3。
默认响应为 code、message、data、trace_id、cost_ms;成功业务码默认零,可通过 Config.SuccessCode 按 Server 设置。不同 Server 不共享响应配置。
@@ -184,6 +184,53 @@ Config.RequestTimeoutMS 是 *int64,缺省 30000 毫秒,显式零禁用。For
完整示例以 pool.PingContext 和 redisClient.Ping(ctx) 构建检查,业务实现可以添加自己的真实依赖探测。
### 5.3 OpenAPI 契约生成
完成路由注册后调用 `server.OpenAPI(options)`,返回 kin-openapi 的 `*openapi3.T`,版本为 [OpenAPI 3.0.3](https://spec.openapis.org/oas/v3.0.3.html)。Title、Version 必填,Servers 可选;Version 是应用 API 版本。生成读取当次已成功注册的路由,不冻结注册、不执行 Controller,也不自动发布文档端点。应在全部路由注册完成后导出;后续注册不更新已经返回的文档。
```go
doc, err := server.OpenAPI(framework.OpenAPIOptions{
Title: "Example API", Version: "1.0.0",
SecuritySchemes: openapi3.SecuritySchemes{
"bearer": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{
Type: "http", Scheme: "bearer", BearerFormat: "JWT",
}},
},
Security: openapi3.SecurityRequirements{{"bearer": []string{}}},
})
if err != nil {
return err // 已在生成边界分类记录,不重复记 error 日志。
}
raw, err := json.MarshalIndent(doc, "", " ")
```
这里 openapi3 来自 `github.com/getkin/kin-openapi/openapi3`,json 来自标准库。调用方负责处理序列化及文件写入错误;完整可运行实现见 [契约导出示例](../examples/openapi/main.go):
```sh
go run ./examples/openapi -out /tmp/ginframework-openapi.json
```
| 声明来源 | 生成内容 |
|---|---|
| 最终路由与 Meta | 方法、带前缀路径、summary、tag;`:id` 转 `{id}`,`*tail` 加 catch-all 扩展 |
| Form 字段 | uri 路径参数、form 查询名、JSON 对象、URL 表单及 multipart;跳过 Meta 与顶层可信注入字段 |
| Controller 第一个返回值 | 成功响应 data Schema,外层保留真实 Envelope;支持指针、嵌套对象、切片、Map 及循环 DTO |
| dc、default | 字段说明、可表达的标量默认值;不执行默认值设置或业务代码 |
| binding | 无条件 required、数值/长度/集合 min/max/len/gt/gte/lt/lte、oneof、email、UUID;切片 dive 后规则应用到元素 |
| 内置错误 | 400 字段校验明细及 413/415/500/504 的安全响应;业务错误映射由应用补充 |
合并来源的语义:GET/HEAD/OPTIONS 只生成路径与查询;有 Body 的方法同时生成可选查询和可选 RequestBody。必填发生在合并、默认值、可信注入之后,因此根 Body 不使用会误拒绝其他来源的 required,而用 `x-gin-required-after-merge` 保留无条件必填清单。普通查询中带 default 的字段不强制出现。JSON Schema 的 required 只表达存在性,不能替代 validator 对零值的检查。
所有非空 binding 声明保留在 `x-gin-binding`。跨字段、自定义、OR、omitempty/omitnil 等规则不冒充等价的标准约束;Map keys/endkeys 的值规则也不自动推断。复杂场景以运行时校验为准,并由应用通过 Customize 补充。固定长度 Go 数组标记 `x-gin-schema-unresolved`;自定义 JSON 序列化类型标记 `x-gin-custom-json`,其形状不自动推断。any 保持开放结构。循环组件同名但定义不一致时明确失败,需使用不同 DTO 名称。没有完整未知字段、字段存在性或自定义序列化分析器。
当前原生类型生成器不支持名称以 Ref 结尾的非结构体别名;框架会返回明确错误,避免反射 panic。此类字段先转换为普通标量对外 DTO。响应侧只推导序列化结构与属性存在性,不把输入 binding 标签当作已经执行的输出校验。
安全声明:Meta `security:"-"` 表示公开操作并覆盖默认要求;`security:"bearer"` 引用单个方案;`security:"bearer,api_key"` 表示两个方案同时满足。Meta 未声明则继承 options.Security。OR 与 OAuth scopes 使用原生 SecurityRequirements 或 Customize。未定义方案、非法文档、无法解析的引用与路径转换均返回错误,不返回半成品;不加载外部引用。安全声明只描述契约,应用必须独立安装对应认证/权限中间件。
`Customize func(Metadata, *openapi3.Operation) error` 在单操作生成后、规范校验前调用,可设置 OperationID、业务错误、请求约束或安全覆盖。Handle/SSE/健康探针等原生路由无法从函数签名可靠推导,默认仅包含 `x-gin-native: true`、路径参数和未推断的 default 响应;应用需补充真实请求、响应媒体类型与 Schema,不能把此占位响应当作完整契约。普通 Controller 若手工写响应,也需在这里覆盖默认 Envelope 声明。
文档和 options 中的数据生成后互不共享到 Server,返回后可由调用方继续编辑;继续编辑后应再次执行 `doc.Validate(ctx)`。如需在线展示,可由应用显式注册原生 `/openapi.json` 路由提供预先序列化的字节,并自行配置访问权限;库不打包 UI、不开后台任务、不持有输出文件。现有 Routes、请求绑定、响应及认证行为均保持原契约,新增依赖固定为 kin-openapi v0.152.0。
## 6. 配置、日志与诊断
### 6.1 配置
+1 -1
View File
@@ -61,7 +61,7 @@
| 高 | 按调用类型逐步回接出站客户端 | 先普通 JSON/表单,再任务提交/进度,最后流式和文件传输;每类保留原始状态、预算和失败处理,不能全仓替换 import |
| 高 | 补齐旧业务响应适配 | 现有多个接口仍接收 network/httpclient/define.Response,需要供应商所属应用提供转换;避免新库长期保存旧响应结构 |
| 中 | 将合适的 CORS 和请求限流技术部分迁入 | 库保持显式配置,应用决定域名名单、身份主体、额度和业务异常;不把固定部署规则纳入核心 |
| 中 | 文档生成消费只读路由快照 | Routes 已提供最终路径;实际需求明确后再接 OpenAPI 展示,不先设计多个文档后端接口 |
| 已完成 | OpenAPI 契约读取注册签名 | OpenAPI 输出请求/响应 Schema、可表达的 binding 约束及显式安全声明;复用 kin-openapi,UI 展示仍由应用装配,详见接入指南 5.3 |
| 低 | 批量注册以降低启动期路由重建开销 | 当前每次提交候选引擎会重建已有路由,逐条注册存在累计开销;优先在应用使用 Group 一次传多个 Controller。缺少启动耗时证据前,不建设复杂增量路由事务层 |
| 暂不整合 | Turnstile、DeepSeek、对象存储和 SSE 代理业务策略 | 固定目标、安全校验、供应商预算、SDK 传输及流事件各有真实差异;复用基础客户端前先验证原契约,不合并为一个供应商大客户端 |
+1 -1
View File
@@ -27,7 +27,7 @@
- 默认响应耗时字段为 cost_ms。原项目响应字段配置、业务错误状态推导及业务 HTTP 中间件需要在回接阶段明确适配并对照实际协议。
- 库通过受信任中间件生成自己的 request_id/trace_id,不信任客户端同名请求头;应用跨服务传播协议另行明确。
- 当前不包含旧 SSE 握手/结束事件、请求后业务 Hook、no-login 和 rate-limit 语义;检测到旧 tag 明确拒绝。流式服务先使用原生 Gin Handler 适配,不静默改变认证或输出协议。
- OpenAPI/Scalar 展示、pprof、CORS 和限流策略尚未迁入本库;应用可在显式 Gin 中间件与路由处装配。文档侧读取 Routes 快照,不要求业务 DTO 引入运行框架。
- OpenAPI 契约由 Server.OpenAPI 从注册签名生成,安全方案由应用声明;既有 Routes 快照兼容保留。Scalar/UI 展示、pprof、CORS 和限流策略仍由应用在显式 Gin 路由/中间件处装配。生成器不执行认证,不隐式发布文档端点,具体约束见接入指南 5.3。
- Redis 实例名、Key、缓存、租约、队列和锁留在应用。Redis Open 返回原生客户端,正常关闭错误由应用首次接收并分类记录。
- 审计插件由应用通过 database.Options.Plugins 显式安装。基础库没有审计 Model、表名和后台身份语义。
- 库保留原生 GORM 方言扩展点;SQLite 用于本地回归,MySQL 的真实连接、方言和项目审计仍需集成环境验证。
+76
View File
@@ -0,0 +1,76 @@
// Command openapi 在不启动 HTTP 服务的情况下导出示例契约。
package main
import (
"encoding/json"
"flag"
"os"
"git.zhangdeman.cn/github/ginframework/fault"
framework "git.zhangdeman.cn/github/ginframework/http"
"git.zhangdeman.cn/github/ginframework/logger"
"github.com/getkin/kin-openapi/openapi3"
"github.com/gin-gonic/gin"
)
const (
codeExportJSON = 990201
codeExportFile = 990202
)
type itemForm struct {
framework.Meta `path:"/items/:id" method:"GET" summary:"获取条目" tag:"items" security:"bearer" dc:"纯文档安全声明;本示例仅导出,不启动业务服务"`
ID int64 `json:"-" uri:"id" binding:"required,min=1" dc:"条目标识"`
}
type itemOutput struct {
ID int64 `json:"id" dc:"条目标识"`
Name string `json:"name" dc:"展示名称"`
}
type items struct{}
// Get 声明可由反射读取的公开响应;文档生成不会调用该方法。
// 入参:ctx 为业务请求,input 为表单;返回示例 DTO 和错误。
func (*items) Get(ctx *gin.Context, input *itemForm) (*itemOutput, error) {
return &itemOutput{ID: input.ID, Name: "example"}, nil
}
// main 显式选择输出路径;生成失败时保留源头日志并设置非零退出码。
func main() {
output := flag.String("out", "openapi.json", "生成文档的输出文件")
flag.Parse()
if err := export(*output); err != nil {
os.Exit(1)
}
}
// export 只装配静态路由和文档,不监听端口;入参为输出路径,返回已记录的错误。
func export(path string) error {
server, err := framework.NewServer(framework.Config{}, framework.Options{})
if err != nil {
return err
}
if err = server.Group("/api", nil, &items{}); err != nil {
return err
}
doc, err := server.OpenAPI(framework.OpenAPIOptions{
Title: "Ginframework example", Version: "1.0.0",
SecuritySchemes: openapi3.SecuritySchemes{"bearer": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "http", Scheme: "bearer", BearerFormat: "JWT"}}},
})
if err != nil {
return err
}
raw, err := json.MarshalIndent(doc, "", " ")
if err != nil {
classified := fault.New(codeExportJSON, "encode exported OpenAPI document failed", err)
logger.RecordError("encode exported OpenAPI document failed", classified)
return classified
}
if err = os.WriteFile(path, raw, 0600); err != nil {
classified := fault.New(codeExportFile, "write exported OpenAPI document failed", err)
logger.RecordError("write exported OpenAPI document failed", classified)
return classified
}
return nil
}
+6
View File
@@ -3,6 +3,7 @@ module git.zhangdeman.cn/github/ginframework
go 1.27.0
require (
github.com/getkin/kin-openapi v0.152.0
github.com/gin-gonic/gin v1.12.0
github.com/go-playground/validator/v10 v10.30.5
github.com/go-sql-driver/mysql v1.10.1
@@ -26,6 +27,8 @@ require (
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-openapi/jsonpointer v0.22.5 // indirect
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
@@ -40,10 +43,13 @@ require (
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/oasdiff/yaml v0.1.1 // indirect
github.com/oasdiff/yaml3 v0.0.14 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
+16
View File
@@ -17,12 +17,22 @@ github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gE
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/getkin/kin-openapi v0.152.0 h1:XRVo77lMRyOGMHf1paMu9lxX3wzuQDZeprssZJnz/x8=
github.com/getkin/kin-openapi v0.152.0/go.mod h1:1+BHDzstro+P5CKtPy1X4PfofnFgmRe6uvMy9+r9fKY=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0=
github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo=
github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -78,6 +88,10 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY=
github.com/oasdiff/yaml v0.1.1/go.mod h1:EYJNoyktvWMJ0Hmhx+6qTaqMOsalUaRGT8Sj1hNcegU=
github.com/oasdiff/yaml3 v0.0.14 h1:aLJee3hxBK2H5wdXd9iPcIXb93Nty1Ge0pT171eHtkw=
github.com/oasdiff/yaml3 v0.0.14/go.mod h1:csto2xfDjYccdUn/yw/bPjj/cYTdp6HtFA0J4TWG+gg=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@@ -91,6 +105,8 @@ github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBP
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+223
View File
@@ -0,0 +1,223 @@
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
}
+196
View File
@@ -0,0 +1,196 @@
package http
import (
"mime/multipart"
"net/http"
"reflect"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
// openAPIRequest 从 Form 描述路径、查询及三类正文,并隐藏由可信注入拥有的顶层字段。
// 入参:op 为本次操作,item 为路由快照,schemas 为本次组件;返回 Schema 生成错误。
func (s *Server) openAPIRequest(op *openapi3.Operation, item route, schemas openapi3.Schemas) error {
fields := contractInputFields(item.input, map[reflect.Type]bool{})
hiddenGo, hiddenJSON := map[string]bool{}, map[string]bool{}
for name := range s.options.TrustedFields {
field, exists := item.input.FieldByName(name)
if !exists {
continue
}
if field.Anonymous && strings.SplitN(field.Tag.Get("json"), ",", 2)[0] == "" {
for _, child := range contractInputFields(field.Type, map[reflect.Type]bool{}) {
hiddenGo[child.Name] = true
hiddenJSON[contractFieldName(child, "json")] = true
}
} else {
hiddenGo[field.Name] = true
hiddenJSON[contractFieldName(field, "json")] = true
}
}
bodyMethod := item.meta.Method == http.MethodPost || item.meta.Method == http.MethodPut || item.meta.Method == http.MethodPatch || item.meta.Method == http.MethodDelete
formBody := openapi3.NewObjectSchema()
urlBody := openapi3.NewObjectSchema()
for _, field := range fields {
if hiddenGo[field.Name] {
continue
}
uri := strings.SplitN(field.Tag.Get("uri"), ",", 2)[0]
if uri != "" && uri != "-" {
for _, parameter := range op.Parameters {
if parameter.Value.Name == uri {
schema, err := contractFieldSchema(field, schemas)
if err != nil {
return err
}
parameter.Value.Schema = schema
parameter.Value.Description = field.Tag.Get("dc")
}
}
}
name := contractFieldName(field, "form")
if name == "-" || (uri != "" && field.Tag.Get("form") == "") {
continue
}
file := contractFileSchema(field.Type)
schema := file
if schema == nil {
var (
err error
)
schema, err = contractFieldSchema(field, schemas)
if err != nil {
return err
}
}
formBody.Properties[name] = schema
if file != nil {
file.Value.Description = field.Tag.Get("dc")
applyContractRules(file.Value, field.Tag.Get("binding"))
continue
}
urlBody.Properties[name] = schema
parameter := openapi3.NewQueryParameter(name)
parameter.Description, parameter.Schema = field.Tag.Get("dc"), schema
parameter.Required = !bodyMethod && requiredContractField(field) && uri == ""
if schema.Value != nil && (schema.Value.Type.Is("object")) {
// Gin 对 Query 中的结构体和 Map 使用 JSON 字符串解码。
parameter.Schema = nil
parameter.Content = openapi3.Content{"application/json": &openapi3.MediaType{Schema: schema}}
} else if schema.Value != nil && schema.Value.Type.Is("array") {
explode := true
parameter.Style, parameter.Explode = "form", &explode
switch field.Tag.Get("collection_format") {
case "csv":
*parameter.Explode = false
case "ssv":
parameter.Style = "spaceDelimited"
*parameter.Explode = false
case "pipes":
parameter.Style = "pipeDelimited"
*parameter.Explode = false
}
}
op.Parameters = append(op.Parameters, &openapi3.ParameterRef{Value: parameter})
}
if !bodyMethod {
return nil
}
body, err := filteredContractSchema(item.input, schemas, hiddenJSON, false)
if err != nil {
return err
}
if len(body.Value.Required) > 0 {
if body.Value.Extensions == nil {
body.Value.Extensions = map[string]any{}
}
publicRequired := []string{}
for _, name := range body.Value.Required {
if body.Value.Properties[name] != nil {
publicRequired = append(publicRequired, name)
}
}
body.Value.Extensions["x-gin-required-after-merge"] = publicRequired
body.Value.Required = nil
}
content := openapi3.Content{"application/json": &openapi3.MediaType{Schema: body}}
if len(formBody.Properties) > 0 {
content["multipart/form-data"] = &openapi3.MediaType{Schema: formBody.NewRef()}
}
if len(urlBody.Properties) > 0 {
content["application/x-www-form-urlencoded"] = &openapi3.MediaType{Schema: urlBody.NewRef()}
}
op.RequestBody = &openapi3.RequestBodyRef{Value: &openapi3.RequestBody{Description: "URI → Query → Body merged before defaults, trusted injection and validation", Content: content}}
return nil
}
// contractInputFields 展开无 form/uri/json 命名的匿名输入,跳过 Meta 和不可导出字段。
// 入参:t 为 Form,visiting 为当前递归路径;返回公开字段清单,不修改业务类型。
func contractInputFields(t reflect.Type, visiting map[reflect.Type]bool) []reflect.StructField {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
fields := []reflect.StructField{}
if t.Kind() != reflect.Struct || visiting[t] {
return fields
}
visiting[t] = true
defer delete(visiting, t)
for index := 0; index < t.NumField(); index++ {
field := t.Field(index)
if field.Type == reflect.TypeOf(Meta{}) {
continue
}
if field.Anonymous && field.Tag.Get("json") == "" && field.Tag.Get("form") == "" && field.Tag.Get("uri") == "" {
fields = append(fields, contractInputFields(field.Type, visiting)...)
continue
}
if field.PkgPath == "" {
fields = append(fields, field)
}
}
return fields
}
// contractFieldSchema 生成绑定字段及字段本身的约束。
// 入参:field 为原字段声明,schemas 为本次组件;返回带说明及校验声明的独立引用。
func contractFieldSchema(field reflect.StructField, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
schema, err := contractSchema(field.Type, schemas)
if err != nil {
return nil, err
}
t := field.Type
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
item, itemErr := contractSchema(t.Elem(), schemas)
if itemErr != nil {
return nil, itemErr
}
schema = openapi3.NewArraySchema().NewRef()
schema.Value.Items = item
}
if schema.Value != nil {
if !schema.Value.Type.Is("object") {
schema.Value.Nullable = false
}
schema.Value.Description = field.Tag.Get("dc")
applyContractRules(schema.Value, field.Tag.Get("binding"))
setContractDefault(schema.Value, field.Tag)
}
return schema, nil
}
// contractFileSchema 将绑定器支持的上传类型映射为 multipart 二进制字段。
// 入参:t 为字段类型;返回文件结构或 nil 表示普通字段。
func contractFileSchema(t reflect.Type) *openapi3.SchemaRef {
if t == reflect.TypeOf(multipart.FileHeader{}) || t == reflect.TypeOf((*multipart.FileHeader)(nil)) {
return openapi3.NewStringSchema().WithFormat("binary").NewRef()
}
if t == reflect.TypeOf([]*multipart.FileHeader{}) {
return openapi3.NewArraySchema().WithItems(openapi3.NewStringSchema().WithFormat("binary")).NewRef()
}
return nil
}
+390
View File
@@ -0,0 +1,390 @@
package http
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3gen"
)
var (
contractEnumTokens = regexp.MustCompile(`'[^']*'|\S+`)
jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
)
// contractSchema 复用原生类型生成器,只补充 dc 和 binding 的静态语义。
// 入参:t 为 DTO 类型,schemas 为本次生成拥有的组件集合;返回 Schema 或不支持的类型错误。
func contractSchema(t reflect.Type, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
return filteredContractSchema(t, schemas, nil, false)
}
// responseContractSchema 按序列化存在性生成响应,不将输入 binding 当作响应校验。
// 入参:t 为响应类型,schemas 为组件集合;返回独立响应结构或类型错误。
func responseContractSchema(t reflect.Type, schemas openapi3.Schemas) (*openapi3.SchemaRef, error) {
return filteredContractSchema(t, schemas, nil, true)
}
// filteredContractSchema 在生成根节点时排除可信注入属性,循环引用的组件也保留相同边界。
// 入参:t 为 DTO,schemas 为组件集合,hidden 为根节点隐藏字段,response 为响应方向。
// 返回:与运行时 JSON 序列化对应的结构或错误,不保留输入对象。
func filteredContractSchema(t reflect.Type, schemas openapi3.Schemas, hidden map[string]bool, response bool) (*openapi3.SchemaRef, error) {
if err := checkContractReferenceTypes(t, map[reflect.Type]bool{}); err != nil {
return nil, err
}
if t.Kind() == reflect.Interface {
return openapi3.NewSchema().WithNullable().NewRef(), nil
}
local := openapi3.Schemas{}
customizer := contractCustomizer(response)
ref, err := openapi3gen.NewSchemaRefForValue(reflect.New(t).Elem().Interface(), local,
openapi3gen.UseAllExportedFields(), openapi3gen.CreateFieldNameGenerator(func(field reflect.StructField, _ string) string { return contractFieldName(field, "json") }), openapi3gen.SchemaCustomizer(func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
if err := customizer(name, t, tag, schema); err != nil {
return err
}
if name == "_root" {
for key := range hidden {
delete(schema.Properties, key)
}
required := []string{}
for _, key := range schema.Required {
if !hidden[key] {
required = append(required, key)
}
}
schema.Required = required
}
return nil
}))
if err != nil {
return nil, err
}
if ref == nil {
return nil, fmt.Errorf("unsupported contract type %s", t)
}
for name, component := range local {
if previous := schemas[name]; previous != nil {
left, leftErr := json.Marshal(previous)
right, rightErr := json.Marshal(component)
if leftErr != nil || rightErr != nil || !bytes.Equal(left, right) {
return nil, fmt.Errorf("conflicting recursive schema name %q", name)
}
}
schemas[name] = component
}
if ref.Value != nil && (t.Kind() == reflect.Ptr || t.Kind() == reflect.Map || t.Kind() == reflect.Slice) {
copy := *ref.Value
ref.Value = &copy
ref.Value.Nullable = true
}
return ref, nil
}
// checkContractReferenceTypes 拒绝原生生成器会作为结构体 Ref 对象处理的标量别名。
// 入参:t 为 DTO 图类型,visited 防止循环重复;返回明确的不支持错误,避免依赖反射 panic。
func checkContractReferenceTypes(t reflect.Type, visited map[reflect.Type]bool) error {
if visited[t] {
return nil
}
visited[t] = true
if t.Kind() != reflect.Struct && strings.HasSuffix(t.Name(), "Ref") {
return fmt.Errorf("non-struct reference-named DTO type %s requires a plain contract type", t)
}
if t.Implements(jsonMarshalerType) || reflect.PointerTo(t).Implements(jsonMarshalerType) {
return nil
}
switch t.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Array, reflect.Map:
return checkContractReferenceTypes(t.Elem(), visited)
case reflect.Struct:
for index := 0; index < t.NumField(); index++ {
field := t.Field(index)
if field.PkgPath != "" && !field.Anonymous || strings.SplitN(field.Tag.Get("json"), ",", 2)[0] == "-" {
continue
}
if err := checkContractReferenceTypes(field.Type, visited); err != nil {
return err
}
}
}
return nil
}
// contractCustomizer 按方向补充字段语义,防止切片 tag 错误应用到元素。
// 入参:response 表示响应序列化方向;返回原生回调,Meta 被排除、复杂序列化被标记。
func contractCustomizer(response bool) openapi3gen.SchemaCustomizerFn {
return func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
if t == reflect.TypeOf(Meta{}) {
return &openapi3gen.ExcludeSchemaSentinel{}
}
if t != reflect.TypeOf(time.Time{}) && (t.Implements(jsonMarshalerType) || reflect.PointerTo(t).Implements(jsonMarshalerType)) {
*schema = openapi3.Schema{Extensions: map[string]any{"x-gin-custom-json": true}}
return nil
}
if t.Kind() == reflect.Slice || t.Kind() == reflect.Map {
schema.Nullable = true
}
if t.Kind() == reflect.Array {
schema.Extensions = map[string]any{"x-gin-schema-unresolved": "fixed array; application schema required"}
}
if t.Kind() != reflect.Struct || !schema.Type.Is("object") {
return nil
}
for _, field := range reflect.VisibleFields(t) {
if field.PkgPath != "" || field.Type == reflect.TypeOf(Meta{}) {
continue
}
label := contractFieldName(field, "json")
property := schema.Properties[label]
if property == nil || property.Value == nil {
continue
}
property = nullableContractRef(field.Type, property)
schema.Properties[label] = property
property.Value.Description = field.Tag.Get("dc")
binding := field.Tag.Get("binding")
if !response && requiredContractField(field) || response && responseFieldRequired(t, field) {
schema.Required = append(schema.Required, label)
}
valueType := field.Type
for valueType.Kind() == reflect.Ptr {
valueType = valueType.Elem()
}
quotedScalar := valueType.Kind() == reflect.Bool || valueType.Kind() >= reflect.Int && valueType.Kind() <= reflect.Float64 || valueType.Kind() == reflect.String
if quotedScalar && property.Value.Extensions["x-gin-custom-json"] != true && strings.Contains(","+field.Tag.Get("json")+",", ",string,") {
nullable := property.Value.Nullable
property.Value = openapi3.NewStringSchema()
property.Value.Nullable = nullable
property.Value.Description = field.Tag.Get("dc")
if !response {
property.Value.Extensions = map[string]any{"x-gin-binding": binding}
}
continue
}
if !response {
applyContractRules(property.Value, binding)
setContractDefault(property.Value, field.Tag)
}
}
return nil
}
}
// nullableContractRef 保留循环引用处的指针/集合可空语义,不把可空标志污染到共享组件。
// 入参:t 为原字段类型,ref 为生成引用;返回允许必要 null 值的引用。
func nullableContractRef(t reflect.Type, ref *openapi3.SchemaRef) *openapi3.SchemaRef {
if t.Kind() == reflect.Ptr {
if strings.HasPrefix(ref.Ref, "#/components/schemas/") {
null := openapi3.NewObjectSchema().WithNullable()
null.Enum = []any{nil}
return &openapi3.SchemaRef{Value: &openapi3.Schema{AnyOf: openapi3.SchemaRefs{ref, null.NewRef()}}}
}
t = t.Elem()
}
if ref.Value == nil {
return ref
}
if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && ref.Value.Items != nil {
ref.Value.Items = nullableContractRef(t.Elem(), ref.Value.Items)
}
if t.Kind() == reflect.Map && ref.Value.AdditionalProperties.Schema != nil {
ref.Value.AdditionalProperties.Schema = nullableContractRef(t.Elem(), ref.Value.AdditionalProperties.Schema)
}
return ref
}
// responseFieldRequired 只标记不会被 omitempty/omitzero 或匿名指针父级省略的字段。
// 入参:root 为所属结构,field 为可见字段;返回是否保证存在对应 JSON 属性。
func responseFieldRequired(root reflect.Type, field reflect.StructField) bool {
tag := "," + field.Tag.Get("json") + ","
if strings.Contains(tag, ",omitempty,") || strings.Contains(tag, ",omitzero,") {
return false
}
for _, index := range field.Index[:len(field.Index)-1] {
root = root.Field(index).Type
if root.Kind() == reflect.Ptr {
return false
}
}
return true
}
// contractFieldName 返回指定绑定方式的静态字段名;入参为字段和 tag,- 表示隐藏。
func contractFieldName(field reflect.StructField, tag string) string {
name := strings.SplitN(field.Tag.Get(tag), ",", 2)[0]
if name == "" {
return field.Name
}
return name
}
// requiredContractField 仅将无默认值的无条件 required 映射为存在性约束。
// 入参:field 为字段声明;返回是否具有可直接表达的必填规则,零值检查仍由 binding 负责。
func requiredContractField(field reflect.StructField) bool {
if _, hasDefault := field.Tag.Lookup("default"); hasDefault {
return false
}
binding := field.Tag.Get("binding")
if strings.Contains(binding, "|") || strings.Contains(","+binding+",", ",omitempty,") || strings.Contains(","+binding+",", ",omitnil,") {
return false
}
for _, rule := range strings.Split(field.Tag.Get("binding"), ",") {
if rule == "required" {
return true
}
}
return false
}
// applyContractRules 将可等价表达的单字段规则映射为标准关键字,其余保留原始扩展。
// 入参:schema 为字段 Schema,binding 为声明;不修改 DTO,不注册运行时规则。
func applyContractRules(schema *openapi3.Schema, binding string) {
if binding == "" || binding == "-" {
return
}
if schema.Extensions == nil {
schema.Extensions = map[string]any{}
}
schema.Extensions["x-gin-binding"] = binding
if schema.Format == "byte" || schema.Format == "binary" {
return
}
// OR 和 omitempty 具有分支语义,不能静默转换成多个 AND 约束。
if strings.Contains(binding, "|") || strings.Contains(","+binding+",", ",omitempty,") || strings.Contains(","+binding+",", ",omitnil,") {
return
}
rules := strings.Split(binding, ",")
for index, rule := range rules {
if rule == "dive" {
if schema.Items != nil && schema.Items.Value != nil {
applyContractRules(schema.Items.Value, strings.Join(rules[index+1:], ","))
}
// Map 的 keys/endkeys 不能当作值约束;完整规则已在扩展中保留。
return
}
key, value, _ := strings.Cut(rule, "=")
switch key {
case "email":
if schema.Type.Is("string") {
schema.Format = "email"
}
case "uuid", "uuid3", "uuid4", "uuid5":
if schema.Type.Is("string") {
schema.Format = "uuid"
}
case "oneof":
values := []any{}
for _, token := range contractEnumTokens.FindAllString(value, -1) {
token = strings.Trim(token, "'")
var (
entry any = token
err error
)
if schema.Type.Is("integer") {
if strings.HasPrefix(token, "-") {
entry, err = strconv.ParseInt(token, 10, 64)
} else {
entry, err = strconv.ParseUint(token, 10, 64)
}
} else if schema.Type.Is("number") {
entry, err = strconv.ParseFloat(token, 64)
}
if err != nil {
values = nil
break
}
values = append(values, entry)
}
schema.Enum = values
case "min", "max", "len", "gte", "lte", "gt", "lt":
applyContractBound(schema, key, value)
}
}
}
// applyContractBound 按值类型区分数值、长度、集合及 Map 大小。
// 入参:schema 为字段结构,rule/value 为服务端规则;无法静态映射时仅保留 binding 扩展。
func applyContractBound(schema *openapi3.Schema, rule string, value string) {
if schema.Type.Is("integer") || schema.Type.Is("number") {
number, err := strconv.ParseFloat(value, 64)
if err != nil {
return
}
switch rule {
case "min", "gte":
schema.WithMin(number)
case "max", "lte":
schema.WithMax(number)
case "len":
schema.WithMin(number).WithMax(number)
case "gt":
schema.WithMin(number).WithExclusiveMin(true)
case "lt":
schema.WithMax(number).WithExclusiveMax(true)
}
return
}
length, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return
}
minimum, maximum := rule == "min" || rule == "gte" || rule == "len", rule == "max" || rule == "lte" || rule == "len"
if rule == "gt" && length < ^uint64(0) {
minimum = true
length++
}
if rule == "lt" && length > 0 {
maximum = true
length--
}
switch {
case schema.Type.Is("string"):
if minimum {
schema.MinLength = length
}
if maximum {
schema.MaxLength = &length
}
case schema.Type.Is("array"):
if minimum {
schema.MinItems = length
}
if maximum {
schema.MaxItems = &length
}
case schema.Type.Is("object"):
if minimum {
schema.MinProps = length
}
if maximum {
schema.MaxProps = &length
}
}
}
// setContractDefault 只记录可安全按 JSON 标量表示的静态 default 声明。
// 入参:schema 为当前字段,tag 为声明;复杂类型默认值由应用补充,不执行反射赋值。
func setContractDefault(schema *openapi3.Schema, tag reflect.StructTag) {
value, exists := tag.Lookup("default")
if !exists {
return
}
if schema.Type.Is("string") {
schema.Default = value
return
}
if schema.Type.Is("integer") || schema.Type.Is("number") || schema.Type.Is("boolean") {
var (
decoded any
)
if json.Unmarshal([]byte(value), &decoded) == nil {
schema.Default = decoded
}
}
}
+321
View File
@@ -0,0 +1,321 @@
package http
import (
"context"
"encoding/json"
"errors"
"mime/multipart"
"net/http/httptest"
"strings"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/gin-gonic/gin"
)
type contractInput struct {
ID int64 `json:"-" uri:"id" binding:"required,min=1"`
Email string `json:"email" form:"email" binding:"required,email" dc:"联系邮箱"`
State string `json:"state" form:"state" binding:"oneof='in progress' done"`
Names []string `json:"names" form:"names" binding:"min=1,max=3,dive,min=2"`
OwnerID int64 `json:"owner_id" form:"owner_id" binding:"required"`
}
type contractForm struct {
Meta `path:"/items/:id" method:"POST" summary:"更新条目" tag:"items" security:"bearer"`
contractInput
}
type contractNode struct {
Name string `json:"name" binding:"min=99"`
Next *contractNode `json:"next,omitempty"`
}
type contractController struct{ calls int }
func (c *contractController) Save(_ *gin.Context, form *contractForm) (*contractNode, error) {
c.calls++
return &contractNode{Name: form.Email}, nil
}
func TestOpenAPICoversMergedRequestResponseAndSecurity(t *testing.T) {
server, err := NewServer(Config{SuccessCode: 10}, Options{TrustedFields: map[string]TrustedField{"OwnerID": func(*gin.Context) (any, error) { return int64(1), nil }}})
if err != nil {
t.Fatal(err)
}
controller := &contractController{}
if err = server.Group("/api", nil, controller); err != nil {
t.Fatal(err)
}
schemes := openapi3.SecuritySchemes{"bearer": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "http", Scheme: "bearer", BearerFormat: "JWT"}}}
options := OpenAPIOptions{Title: "Example", Version: "1.0", SecuritySchemes: schemes}
doc, err := server.OpenAPI(options)
if err != nil {
t.Fatal(err, errors.Unwrap(err))
}
if controller.calls != 0 {
t.Fatal("generation executed controller")
}
operation := doc.Paths.Value("/api/items/{id}").Post
if operation.Summary != "更新条目" || operation.Tags[0] != "items" {
t.Fatal("metadata lost")
}
if operation.Security == nil || len(*operation.Security) != 1 {
t.Fatal("security declaration missing")
}
if _, ok := (*operation.Security)[0]["bearer"]; !ok {
t.Fatal("bearer requirement lost")
}
for _, parameter := range operation.Parameters {
if parameter.Value.Name == "owner_id" {
t.Fatal("trusted identity exposed as client input")
}
if parameter.Value.In == "path" && (!parameter.Value.Required || !parameter.Value.Schema.Value.Type.Is("integer") || *parameter.Value.Schema.Value.Min != 1) {
t.Fatal("path schema lost")
}
if parameter.Value.In == "query" && parameter.Value.Required {
t.Fatal("query cannot be independently required when body can supply it")
}
}
body := operation.RequestBody.Value.Content["application/json"].Schema.Value
if body.Properties["Meta"] != nil || body.Properties["owner_id"] != nil {
t.Fatal("framework/trusted fields leaked into body")
}
if len(body.Required) != 0 || body.Extensions["x-gin-required-after-merge"] == nil {
t.Fatal("merged-source presence was misrepresented")
}
if body.Properties["email"].Value.Format != "email" || body.Properties["email"].Value.Description != "联系邮箱" {
t.Fatal("field contract missing")
}
if body.Properties["state"].Value.Enum[0] != "in progress" {
t.Fatal("quoted enum split incorrectly")
}
array := body.Properties["names"].Value
if array.MinItems != 1 || *array.MaxItems != 3 || array.Items.Value.MinLength != 2 || array.Items.Value.MaxLength != nil {
t.Fatal("collection constraints applied to wrong level")
}
if err = doc.Validate(context.Background()); err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
request := httptest.NewRequest("POST", "/api/items/1", strings.NewReader(`{"email":"a@example.test","state":"done","names":["ok"]}`))
request.Header.Set("Content-Type", "application/json")
server.Handler().ServeHTTP(recorder, request)
if recorder.Code != 200 {
t.Fatalf("unexpected actual response %d: %s", recorder.Code, recorder.Body.String())
}
var (
actual any
)
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
t.Fatal(err)
}
response := operation.Responses.Status(200).Value.Content["application/json"].Schema.Value
if response.Properties["data"].Value.Properties["name"].Value.MinLength != 0 {
t.Fatal("input rules incorrectly constrain unvalidated output")
}
if err = response.VisitJSON(actual); err != nil {
t.Fatalf("generated response disagrees with actual wire JSON: %v", err)
}
if response.Properties["data"].Value.Properties["next"].Ref == "" && response.Properties["data"].Value.Properties["next"].Value == nil {
t.Fatal("recursive response lost")
}
// 返回的文档和选项均不共享到 Server;冻结后也能再次生成。
doc.Components.SecuritySchemes["bearer"].Value.Scheme = "basic"
delete(body.Properties, "email")
next, err := server.OpenAPI(options)
if err != nil {
t.Fatal(err)
}
if schemes["bearer"].Value.Scheme != "bearer" || next.Paths.Value("/api/items/{id}").Post.RequestBody.Value.Content["application/json"].Schema.Value.Properties["email"] == nil {
t.Fatal("document mutation escaped snapshot")
}
}
type contractQueryForm struct {
Meta `path:"/search" method:"GET" security:"-"`
Term string `json:"term" form:"q" binding:"required,min=2"`
Page int `json:"page" form:"page" binding:"required,min=1" default:"1"`
Maybe string `json:"maybe" form:"maybe" binding:"omitempty,min=3"`
Bytes []byte `json:"bytes" form:"bytes" binding:"min=1"`
Filter struct {
Active bool `json:"active"`
} `json:"filter" form:"filter"`
}
type contractUploadForm struct {
Meta `path:"/files" method:"POST"`
File *multipart.FileHeader `json:"-" form:"file" binding:"required"`
}
type contractOtherController struct{}
func (*contractOtherController) Search(*gin.Context, *contractQueryForm) (map[string]any, error) {
return nil, nil
}
func (*contractOtherController) Upload(*gin.Context, *contractUploadForm) (any, error) {
return nil, nil
}
func TestOpenAPIQueryFilesNativeOverridesAndNoImplicitPublication(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if err := server.Group("", nil, &contractOtherController{}); err != nil {
t.Fatal(err)
}
if err := server.Handle("GET", "/stream/*tail", func(*gin.Context) {}); err != nil {
t.Fatal(err)
}
opts := OpenAPIOptions{Title: "Contract", Version: "v1", SecuritySchemes: openapi3.SecuritySchemes{"key": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "apiKey", In: "header", Name: "X-API-Key"}}}, Security: openapi3.SecurityRequirements{{"key": []string{}}}, Customize: func(meta Metadata, op *openapi3.Operation) error {
if meta.Path == "/stream/*tail" {
op.Responses = openapi3.NewResponses(openapi3.WithName("200", openapi3.NewResponse().WithDescription("SSE stream").WithContent(openapi3.Content{"text/event-stream": &openapi3.MediaType{Schema: openapi3.NewStringSchema().NewRef()}})))
}
return nil
}}
doc, err := server.OpenAPI(opts)
if err != nil {
t.Fatal(err)
}
search := doc.Paths.Value("/search").Get
if search.RequestBody != nil || search.Security == nil || len(*search.Security) != 0 {
t.Fatal("GET body or public security override incorrect")
}
for _, ref := range search.Parameters {
parameter := ref.Value
switch parameter.Name {
case "q":
if !parameter.Required || parameter.Schema.Value.MinLength != 2 {
t.Fatal("required query constraint missing")
}
case "page":
if parameter.Required || parameter.Schema.Value.Default != float64(1) {
t.Fatal("default incorrectly requires query input")
}
case "maybe":
if parameter.Schema.Value.MinLength != 0 || parameter.Schema.Value.Extensions["x-gin-binding"] == nil {
t.Fatal("conditional rule falsely strengthened")
}
case "filter":
if parameter.Schema != nil || parameter.Content["application/json"] == nil {
t.Fatal("structured query JSON representation lost")
}
case "bytes":
if !parameter.Schema.Value.Type.Is("array") || parameter.Schema.Value.MinItems != 1 || !parameter.Schema.Value.Items.Value.Type.Is("integer") {
t.Fatal("URL byte slice incorrectly described as base64 JSON string")
}
}
}
file := doc.Paths.Value("/files").Post.RequestBody.Value.Content["multipart/form-data"].Schema.Value.Properties["file"].Value
if file.Format != "binary" {
t.Fatal("multipart upload described as internal FileHeader")
}
stream := doc.Paths.Value("/stream/{tail}").Get
if stream.Extensions["x-gin-native"] != true || stream.Parameters[0].Value.Extensions["x-gin-catch-all"] != true || stream.Responses.Status(200).Value.Content["text/event-stream"] == nil {
t.Fatal("native contract override lost")
}
if err = server.Handle("GET", "/after-generation", func(*gin.Context) {}); err != nil {
t.Fatal("document generation froze registration", err)
}
recorder := httptest.NewRecorder()
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/openapi.json", nil))
if recorder.Code != 404 {
t.Fatal("documentation was implicitly published")
}
}
func TestOpenAPIRejectsInvalidOrIncompleteDeclarations(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if _, err := server.OpenAPI(OpenAPIOptions{}); err == nil {
t.Fatal("missing info accepted")
}
if err := server.Group("", nil, &contractController{}); err != nil {
t.Fatal(err)
}
options := OpenAPIOptions{Title: "Contract", Version: "v1"}
if doc, err := server.OpenAPI(options); err == nil || doc != nil {
t.Fatal("undefined bearer scheme accepted")
}
options.Customize = func(_ Metadata, op *openapi3.Operation) error {
requirements := openapi3.SecurityRequirements{}
op.Security = &requirements
return nil
}
if _, err := server.OpenAPI(options); err != nil {
t.Fatal("explicit native security override rejected", err, errors.Unwrap(err))
}
sentinel := errors.New("contract customization failed")
options.Customize = func(Metadata, *openapi3.Operation) error { return sentinel }
if _, err := server.OpenAPI(options); !errors.Is(err, sentinel) {
t.Fatal("customizer cause lost")
}
options.Customize = func(_ Metadata, op *openapi3.Operation) error { op.Responses = openapi3.NewResponses(); return nil }
if doc, err := server.OpenAPI(options); err == nil || doc != nil {
t.Fatal("invalid final document accepted")
}
native, _ := NewServer(Config{}, Options{})
if err := native.Handle("GET", "/raw", func(*gin.Context) {}); err != nil {
t.Fatal(err)
}
doc, err := native.OpenAPI(OpenAPIOptions{Title: "Native", Version: "1"})
if err != nil {
t.Fatal(err)
}
if len(doc.Paths.Value("/raw").Get.Responses.Default().Value.Content) != 0 {
t.Fatal("native response schema invented")
}
}
type recursiveValue struct {
Age *int `json:"age,string"`
Object struct {
Enabled bool `json:"enabled"`
} `json:"object"`
Next *recursiveValue `json:"next"`
Children []*recursiveValue `json:"children"`
Values map[string]*recursiveValue `json:"values"`
}
type recursiveForm struct {
Meta `path:"/recursive" method:"GET"`
}
type recursiveController struct{}
func (*recursiveController) Get(*gin.Context, *recursiveForm) (recursiveValue, error) {
return recursiveValue{Children: []*recursiveValue{nil, {}}, Values: map[string]*recursiveValue{"none": nil}}, nil
}
func TestOpenAPIRecursiveValueKeepsNullableFieldsAndCollectionItems(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if err := server.Group("", nil, &recursiveController{}); err != nil {
t.Fatal(err)
}
doc, err := server.OpenAPI(OpenAPIOptions{Title: "Recursive", Version: "1"})
if err != nil {
t.Fatal(err, errors.Unwrap(err))
}
recorder := httptest.NewRecorder()
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/recursive", nil))
var (
actual any
)
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
t.Fatal(err)
}
schema := doc.Paths.Value("/recursive").Get.Responses.Status(200).Value.Content["application/json"].Schema.Value
if err = schema.VisitJSON(actual); err != nil {
t.Fatalf("recursive nulls disagree with wire JSON: %v", err)
}
}
type contractScalarRef string
type unsupportedReferenceOutput struct {
Reference contractScalarRef `json:"reference"`
}
type unsupportedReferenceController struct{}
func (*unsupportedReferenceController) Search(*gin.Context, *contractQueryForm) (unsupportedReferenceOutput, error) {
return unsupportedReferenceOutput{}, nil
}
func TestOpenAPIUnsupportedReferenceAliasReturnsError(t *testing.T) {
server, _ := NewServer(Config{}, Options{})
if err := server.Group("", nil, &unsupportedReferenceController{}); err != nil {
t.Fatal(err)
}
if doc, err := server.OpenAPI(OpenAPIOptions{Title: "Reference", Version: "1"}); err == nil || doc != nil {
t.Fatal("unsupported scalar Ref alias did not return an error")
}
}
+10
View File
@@ -47,6 +47,16 @@ const (
codeHealthConfig = 900429
codeReadinessCheck = 900430
codeRequestCancelled = 900431
codeOpenAPIOptions = 900432
codeOpenAPISchema = 900433
codeOpenAPIPath = 900434
codeOpenAPICustomize = 900435
codeOpenAPIValidate = 900436
codeOpenAPICopy = 900437
codeOpenAPISecurity = 900438
codeOpenAPIMethod = 900439
codeOpenAPIDuplicate = 900440
codeOpenAPIResponse = 900441
)
// PublicError 是业务显式允许公开的错误,不包含原始原因文本。
+5 -2
View File
@@ -20,7 +20,7 @@ import (
// Meta 通过 Form 内嵌字段的 tag 声明路由,Input 不依赖本包。
type Meta struct{}
// Metadata 是路由注册完成后的只读快照,可供应用生成 OpenAPI 文档。
// Metadata 是路由注册完成后的轻量只读快照,完整契约通过 Server.OpenAPI 生成。
type Metadata struct {
Method string `json:"method" dc:"大写 HTTP 方法"`
Path string `json:"path" dc:"包含分组前缀的最终路径"`
@@ -31,6 +31,9 @@ type Metadata struct {
type route struct {
meta Metadata `dc:"不可变路由元数据"`
handlers []gin.HandlerFunc `dc:"启动时装配的路由处理链"`
input reflect.Type `dc:"普通 Controller 的 Form 类型,原生路由为空"`
output reflect.Type `dc:"普通 Controller 的公开结果类型,原生路由为空"`
security string `dc:"Meta 声明的文档安全要求,不执行认证"`
}
// TrustedField 从可信认证上下文读取一个公共字段,不读取客户端原始输入。
@@ -97,7 +100,7 @@ func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers
verb = strings.ToUpper(strings.TrimSpace(verb))
handlers := append([]gin.HandlerFunc(nil), middleware...)
handlers = append(handlers, handler)
planned = append(planned, route{meta: Metadata{Method: verb, Path: path.Join("/", prefix, meta.Tag.Get("path")), Summary: meta.Tag.Get("summary"), Tag: meta.Tag.Get("tag")}, handlers: handlers})
planned = append(planned, route{meta: Metadata{Method: verb, Path: path.Join("/", prefix, meta.Tag.Get("path")), Summary: meta.Tag.Get("summary"), Tag: meta.Tag.Get("tag")}, handlers: handlers, input: formType, output: signature.Out(0), security: meta.Tag.Get("security")})
}
}
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.