From 3196e45a0128b106e338069def4719adec66b184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 26 Nov 2026 20:41:33 -0800 Subject: [PATCH 1/5] =?UTF-8?q?feat(http)!:=20=E8=A1=A5=E9=BD=90=E6=A0=B8?= =?UTF-8?q?=E5=BF=83=E8=AF=B7=E6=B1=82=E5=A4=84=E7=90=86=E4=B8=8E=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加安全字段校验提示、请求预算和就绪/存活探针, 让绑定、数据库、Redis 和出站响应解码保留可信诊断上下文。 补充完整应用装配及逆序清理示例,同步接入和迁移文档。 验证:make verify、make race-check 全部通过。 BREAKING CHANGE: 普通 Controller 默认启用 30 秒协作式请求预算, 可用 request_timeout_ms: 0 或 max-exec-time:"0" 关闭; 字段校验失败的 400 响应增加安全字段明细。 --- README.md | 8 + database/connection.go | 20 +- docs/getting-started.md | 58 ++++- docs/integration-optimization-review.md | 2 + docs/migration.md | 9 +- examples/application/config.yml | 21 ++ examples/application/main.go | 188 ++++++++++++++++ examples/application/main_test.go | 108 +++++++++ http/budget.go | 33 +++ http/context_flow_test.go | 161 ++++++++++++++ http/health.go | 103 +++++++++ http/p1_test.go | 277 ++++++++++++++++++++++++ http/request/body.go | 10 +- http/request/context.go | 22 ++ http/request/form.go | 92 ++++---- http/request/validation.go | 164 ++++++++++++++ http/response.go | 13 ++ http/routes.go | 43 +++- http/server.go | 12 + httpclient/request.go | 17 +- internal/failure/error.go | 8 + redis/client.go | 4 +- 22 files changed, 1294 insertions(+), 79 deletions(-) create mode 100644 examples/application/config.yml create mode 100644 examples/application/main.go create mode 100644 examples/application/main_test.go create mode 100644 http/budget.go create mode 100644 http/context_flow_test.go create mode 100644 http/health.go create mode 100644 http/p1_test.go create mode 100644 http/request/context.go create mode 100644 http/request/validation.go diff --git a/README.md b/README.md index 43e90e6..613433b 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,14 @@ go run ./examples/minimal 请求 `http://127.0.0.1:8080/example/ping?name=world`。不需要启动 MySQL 或 Redis。消费项目的分支版本会被 Go 解析为固定伪版本,后续升级选择已审核提交或已发布 tag。 +完整资源装配、健康检查和退出示例: + +```sh +go run ./examples/application -config examples/application/config.yml +``` + +普通 Controller 默认有 30 秒合作式预算;校验错误提供安全字段提示。健康检查需由应用显式注册并在依赖就绪后置为 ready,详见接入指南。 + ## 开发与验证 先读取 [AGENTS.md](AGENTS.md) 和 [工程技术规约](docs/standards/technical-specification.md)。 diff --git a/database/connection.go b/database/connection.go index 915269f..48d96f0 100644 --- a/database/connection.go +++ b/database/connection.go @@ -79,12 +79,12 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, maxIdle = *cfg.MaxIdle } if cfg.ProbeTimeoutMS < 0 || maxOpen < 0 || maxIdle < 0 || cfg.Port < 0 || cfg.Port > 65535 || (maxOpen > 0 && maxIdle > maxOpen) { - return nil, fault.Wrap(CodeConfig, "validate database configuration failed", errors.New("invalid pool, port or probe setting")) + return nil, fault.WrapContext(ctx, CodeConfig, "validate database configuration failed", errors.New("invalid pool, port or probe setting")) } dialect := options.Dialector if dialect == nil { if cfg.Host == "" || cfg.Database == "" { - return nil, fault.Wrap(CodeTarget, "validate MySQL target failed", errors.New("MySQL host and database are required")) + return nil, fault.WrapContext(ctx, CodeTarget, "validate MySQL target failed", errors.New("MySQL host and database are required")) } if cfg.Port == 0 { cfg.Port = 3306 @@ -97,7 +97,7 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, } location, locationErr := time.LoadLocation(cfg.Timezone) if locationErr != nil { - return nil, fault.Wrap(CodeTimezone, "resolve MySQL timezone failed", locationErr) + return nil, fault.WrapContext(ctx, CodeTimezone, "resolve MySQL timezone failed", locationErr) } driver := mysqlDriver.NewConfig() driver.User, driver.Passwd, driver.Net, driver.Addr, driver.DBName = cfg.Username, cfg.Password, "tcp", net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)), cfg.Database @@ -110,18 +110,18 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, if openErr != nil { if orm != nil { if pool, poolErr := orm.DB(); poolErr == nil { - openErr = errors.Join(openErr, fault.Wrap(CodeClose, "close failed database pool failed", pool.Close())) + openErr = errors.Join(openErr, fault.WrapContext(ctx, CodeClose, "close failed database pool failed", pool.Close())) } } - return nil, fault.Wrap(CodeOpen, "open database failed", openErr) + return nil, fault.WrapContext(ctx, CodeOpen, "open database failed", openErr) } pool, poolErr := orm.DB() if poolErr != nil { - return nil, fault.Wrap(CodePool, "resolve database pool failed", poolErr) + return nil, fault.WrapContext(ctx, CodePool, "resolve database pool failed", poolErr) } defer func() { if err != nil { - err = errors.Join(err, fault.Wrap(CodeClose, "close pending database pool failed", pool.Close())) + err = errors.Join(err, fault.WrapContext(ctx, CodeClose, "close pending database pool failed", pool.Close())) } }() pool.SetMaxOpenConns(maxOpen) @@ -132,14 +132,14 @@ func Open(ctx context.Context, cfg Config, options Options) (result *Connection, probe, cancel := context.WithTimeout(ctx, time.Duration(cfg.ProbeTimeoutMS)*time.Millisecond) defer cancel() if err = pool.PingContext(probe); err != nil { - return nil, fault.Wrap(CodeProbe, "probe database failed", err) + return nil, fault.WrapContext(ctx, CodeProbe, "probe database failed", err) } for _, plugin := range options.Plugins { if plugin == nil { - return nil, fault.Wrap(CodePlugin, "install database plugin failed", errors.New("database plugin is nil")) + return nil, fault.WrapContext(ctx, CodePlugin, "install database plugin failed", errors.New("database plugin is nil")) } if err = orm.Use(plugin); err != nil { - return nil, fault.Wrap(CodePlugin, "install database plugin failed", err) + return nil, fault.WrapContext(ctx, CodePlugin, "install database plugin failed", err) } } return &Connection{root: orm, pool: pool}, nil diff --git a/docs/getting-started.md b/docs/getting-started.md index 97601ae..9ded748 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -35,8 +35,8 @@ go mod tidy | `database/sqllog` | GORM 官方 Trace 与 SQL 脱敏 | 自建原生 GORM 的可选日志适配 | | `redis` | 原生 Redis 客户端创建与探测 | 应用装配根 | | `redis/commandlog` | 官方 Hook 与 Pipeline 执行观测 | 自建原生 Redis 的可选日志适配 | -| `http` | Gin Server、Form/Meta、响应、可信注入、原生路由、流式截止与排空 | HTTP 入口 | -| `http/request` | URI/Query/Body、multipart、正文限制与 validator 规则 | 自定义请求适配 | +| `http` | Gin Server、Form/Meta、响应、可信注入、健康检查、合作式预算与排空 | HTTP 入口 | +| `http/request` | URI/Query/Body、multipart、正文限制、Context 校验与字段级提示 | 自定义请求适配 | | `httpclient` | 出站连接池、请求编码、有界响应、原生流式与安全流水 | 第三方服务适配 | @@ -87,7 +87,7 @@ if err = server.Group("/api", nil, &Example{}); err != nil { } ``` -完整路由为 `GET /api/ping`。Form 的 path 不重复声明入口前缀。支持的 tag 是 `path`、`method`、`summary`、`tag`、`max-body-bytes`;method 可用逗号声明多个方法。Controller 使用指针实例,方法签名为 `func(*gin.Context, Form或*Form) (公开结果, error)`。 +完整路由为 `GET /api/ping`。Form 的 path 不重复声明入口前缀。支持的 tag 是 `path`、`method`、`summary`、`tag`、`max-body-bytes`、`max-exec-time`;method 可用逗号声明多个方法。Controller 使用指针实例,方法签名为 `func(*gin.Context, Form或*Form) (公开结果, error)`。 同一 Group 可一次传多个 Controller;整批检查成功后才提交。`Handler()`、`Serve(listener)` 或 `Shutdown(ctx)` 会冻结后续注册。不能在服务运行中继续添加路由。`Routes()` 返回包含最终完整路径的副本,可交给应用文档生成器。 @@ -101,11 +101,19 @@ if err = server.Group("/api", nil, &Example{}); err != nil { 顺序固定为 URI → Query → Body → 默认值 → 可信字段 → 一次最终校验。GET/HEAD/OPTIONS 不使用 Body 覆盖参数;POST/PUT/PATCH/DELETE 支持 JSON、URL 编码表单及 multipart。JSON 支持 `+json` 类型,拒绝多份根 JSON。 -默认请求正文上限 4 MiB,单路由可通过 `max-body-bytes:"8388608"` 调整,单位字节。正文超限返回 413,不支持的媒体类型返回 415,一般绑定/校验失败返回安全 400。上传文件字段可用 multipart.FileHeader、*multipart.FileHeader 或 []*multipart.FileHeader。 +默认请求正文上限 4 MiB,单路由可通过 `max-body-bytes:"8388608"` 调整,单位字节。正文超限返回 413,不支持的媒体类型返回 415,一般绑定失败返回安全 400;字段约束失败返回 400,data.fields 包含安全的字段名、规则和提示。上传文件字段可用 multipart.FileHeader、*multipart.FileHeader 或 []*multipart.FileHeader。 Form 的 default tag 延续 go-defaults 行为,标量零值可能被认为缺省;需区分“未传”和“显式零值”时使用指针并补对应测试。没有 JSON 全字段存在性跟踪。 -自定义原生 Gin Handler 可使用 `request.Form.Parse(ctx, &form)` 一次完成绑定、默认值和校验;若要在中间注入可信字段,顺序是 `Bind → defaults.SetDefaults(&form) → 应用显式注入可信字段 → Validate`,不能再重复 Parse。这里 defaults 是 github.com/mcuadros/go-defaults;Bind 和 Validate 本身不会设置默认值。自定义字段规则通过 `request.RegisterValidation` 在启动期登记,规则函数使用 validator/v10 原生类型。 +自定义原生 Gin Handler 可使用 `request.Form.Parse(ctx, &form)` 一次完成绑定、默认值和校验;若要在中间注入可信字段,顺序是 `Bind → defaults.SetDefaults(&form) → 应用显式注入可信字段 → ValidateContext(ctx.Request.Context(), &form)`,不能再重复 Parse。这里 defaults 是 github.com/mcuadros/go-defaults;Bind 和 ValidateContext 本身不会设置默认值。Validate(receiver) 保留为无请求来源的兼容入口;HTTP/Worker 的显式校验优先使用 ValidateContext,保留标准上下文诊断。自定义字段规则通过 `request.RegisterValidation` 在启动期登记,规则函数使用 validator/v10 原生类型。 + +字段提示使用 json/form/uri 中声明的公开名称,嵌入 Input 不增加对象层级,集合位置统一为 [],例如 profile.email、items[].email。返回 rule 但不返回校验参数、原始输入、Map 键和内部 Form 类型名;常见规则有默认英文提示,可用字段静态 err 标签提供安全文案。未知映射使用 request。调用方可通过 errors.As 继续识别 request.ValidationError 和底层 validator.ValidationErrors。 + +校验错误示例: + +```json +{"code":400,"message":"Validation failed","data":{"fields":[{"field":"email","rule":"email","message":"Invalid email address"}]},"trace_id":"trusted-request-id","cost_ms":1} +``` ### 4.2 可信身份 @@ -150,7 +158,31 @@ err := server.Handle(http.MethodGet, "/events", 这里 http 是标准库 net/http,framework 是框架 http 包。Deadline 只派生上下文,不缓冲或替换 Writer;业务须监听取消并停止写出。生产事件内容、连接确认、结束事件及业务 Hook 由应用定义。 -旧 `is-sse`、`is-ws`、`max-exec-time`、`rate-limit`、`no-login`、`hook-sync`、`output_strict` tag 当前明确拒绝。WebSocket 没有内置实现。不要把旧 Form 原样搬入后假定安全策略会自动生效。 +旧 `is-sse`、`is-ws`、`rate-limit`、`no-login`、`hook-sync`、`output_strict` tag 当前明确拒绝。WebSocket 没有内置实现。不要把旧 Form 原样搬入后假定安全策略会自动生效。 + +### 5.1 普通 Controller 请求预算 + +Config.RequestTimeoutMS 是 *int64,缺省 30000 毫秒,显式零禁用。Form 的 max-exec-time tag 按秒覆盖本路由,0 禁用;负值和时长溢出在注册期拒绝。构造时复制配置,不受调用方后续修改指针影响。 + +预算从 Controller 适配函数开始,覆盖参数绑定、可信注入、校验和业务调用;此前的全局/组中间件如需预算,由应用显式传递 Context。预算会派生到数据库会话、Redis 命令及出站请求。截止后处理函数合作退出,框架返回安全的 504;客户端取消不继续写响应。 + +这是合作式预算,不是强杀或后台脱离执行:处理函数、依赖和原始正文读取必须遵守取消;忽略 Context 的函数或阻塞 Reader 可能延长请求。框架在它们结束前不会释放其依赖,也不会跨协程复用 Gin Writer。已写出的响应不再覆盖。不能把它当作网络层慢上传硬截止,监听器/反向代理的网络超时由部署显式配置。 + +原生 Handle 路由不自动套用普通 Controller 预算,SSE 使用 Deadline 和请求取消;标准超时响应不替换流式 Writer。 + +### 5.2 存活与就绪检查 + +启动期调用 server.RegisterHealth("/_health", framework.HealthOptions{...}),一次注册 GET /_health/live 和 GET /_health/ready。两条路由也受冲突检查和注册冻结约束。 + +- live 仅表示当前进程能够处理请求,不主动探测数据库或 Redis;正常返回 200。 +- ready 初始返回 503。应用完成全部依赖创建、业务装配及路由注册后调用 SetReady(true),探测全部成功才返回 200。 +- HealthOptions.Checks 是启动期固定的 ReadinessCheck 列表,每项包含安全 Name 和 Check func(context.Context) error。复用已创建的池,不新建连接;失败只公开名称和 ready=false,不输出地址、密码或原始错误。 +- TimeoutMS 是本次就绪探测的合作式总预算,缺省 1000 毫秒,回调必须响应 Context;没有后台探测 goroutine 或动态注册中心。 +- 部署开始摘流时调用 SetReady(false);Shutdown 自动置 false,随后停止接收和排空请求。 + +健康路由仍经过应用配置的全局中间件。认证中间件应显式按部署策略允许探针,或将其放在受控内网入口,框架不自动绕过认证。 + +完整示例以 pool.PingContext 和 redisClient.Ping(ctx) 构建检查,业务实现可以添加自己的真实依赖探测。 ## 6. 配置、日志与诊断 @@ -196,7 +228,7 @@ Name 和 Path 必填;MaxAge 单位秒,非正值使用三天。文件轮转 ### 6.3 Context 与内部错误 -后台入口用 `diagnostic.With(ctx, diagnostic.Snapshot{...})` 建立可信标量快照;无请求来源时不要伪造 request_id。`diagnostic.From(ctx)` 返回副本。普通业务能力使用标准 context.Context,避免为了日志构造伪 Gin 请求。 +后台入口用 `diagnostic.With(ctx, diagnostic.Snapshot{...})` 建立可信标量快照;无请求来源时不要伪造 request_id。`diagnostic.From(ctx)` 返回副本。普通业务能力使用标准 context.Context,避免为了日志构造伪 Gin 请求。请求绑定、校验、可信注入、连接启动错误和出站错误均在接收处使用该上下文记录;出站 Response 只保存可信标量诊断副本,让后续 DecodeJSON 的错误仍可关联原请求,不持有 HTTP 请求或可变 Context。 `fault.New(code, summary, cause)` 只创建内部错误,支持 errors.Is/As 和 Unwrap,不自动写日志。应用主动创建此类错误时需在源头调用 `logger.RecordErrorContext(ctx, 英文摘要, err)` 一次,上层只传播。源头错误码使用稳定具名常量;不得作为公开 HTTP 业务码输出。 @@ -302,6 +334,18 @@ Options.Transport 可以借用原生 RoundTripper 以支持特定代理和证书 本库不是旧包的 import 兼容层。旧 Response 类型、HTTP 状态映射、SSE 事件、请求后 Hook、认证和文档展示都需要显式适配,见 [迁移清单](migration.md)。 +### 9.1 完整装配示例 + +```sh +go run ./examples/application -config examples/application/config.yml +``` + +[完整示例](../examples/application/main.go) 和 [示例配置](../examples/application/config.yml) 演示:配置日志 → 创建可选数据库/Redis → 创建复用出站客户端 → 注册 Controller/健康检查 → 全部成功后 SetReady(true) → 监听。默认配置无需数据库或 Redis 即可运行,取消配置注释后启用真实依赖;配置了任一依赖但创建失败必须停止启动。 + +装配中的资源先由局部 resources 持有,失败关闭已创建部分;示例没有全局服务容器或运行期查找依赖。注册/监听/Serve 提前失败也会排空 HTTP;正常退出先置未就绪、取消并等待处理函数结束,再逆序关闭出站空闲池、Redis、数据库,最后关闭日志。 + +该示例没有 Worker;消费应用有 Worker 时必须在连接释放前取消并等待它们完成。示例及测试覆盖无外部依赖启动、失败回收和退出,真实 MySQL 与业务插件仍须集成环境验证。 + ## 10. 文档同步与验收 任何能力新增、移除或行为变化,在同一提交中完成:能力表、所属章节、公开 API 用法、配置及缺省值、所有权/退出约束、兼容影响、示例或实际验证说明。删除能力须同时移除陈旧命令和安装说明;重命名须核对所有链接。README 和 AGENTS 只保留本指南入口,技术约束唯一维护在规约正文。 diff --git a/docs/integration-optimization-review.md b/docs/integration-optimization-review.md index 5f558c4..2cbd788 100644 --- a/docs/integration-optimization-review.md +++ b/docs/integration-optimization-review.md @@ -52,6 +52,8 @@ 这些改动有明确现有调用,不引入通用生命周期容器、泛型 Option 解析器或动态策略注册表。性能收益只确认移除了重复工作,没有据此宣称已测得吞吐提升。 +核心 P1 后续补齐:字段级安全提示、请求 Context 诊断、普通 Controller 合作式预算、存活/就绪探测和完整资源装配示例均已提供,具体契约以 [接入使用指南](getting-started.md) 为准。 + ## 4. 适合继续整合,但本轮不扩大的范围 | 优先级 | 建议 | 边界与依据 | diff --git a/docs/migration.md b/docs/migration.md index e96dde6..4386648 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -26,12 +26,19 @@ - 请求 `default` tag 延续原有 go-defaults 行为:标量零值可能被视为缺省。对需区分未传和显式零值的字段使用指针,接入前补对应用例;不声称库已实现 JSON 全字段存在性跟踪。 - 默认响应耗时字段为 cost_ms。原项目响应字段配置、业务错误状态推导及业务 HTTP 中间件需要在回接阶段明确适配并对照实际协议。 - 库通过受信任中间件生成自己的 request_id/trace_id,不信任客户端同名请求头;应用跨服务传播协议另行明确。 -- 当前不包含旧 SSE 握手/结束事件、请求后业务 Hook、反射路由超时、no-login 和 rate-limit 语义;检测到旧 tag 明确拒绝。流式服务先使用原生 Gin Handler 适配,不静默改变认证或输出协议。 +- 当前不包含旧 SSE 握手/结束事件、请求后业务 Hook、no-login 和 rate-limit 语义;检测到旧 tag 明确拒绝。流式服务先使用原生 Gin Handler 适配,不静默改变认证或输出协议。 - OpenAPI/Scalar 展示、pprof、CORS 和限流策略尚未迁入本库;应用可在显式 Gin 中间件与路由处装配。文档侧读取 Routes 快照,不要求业务 DTO 引入运行框架。 - Redis 实例名、Key、缓存、租约、队列和锁留在应用。Redis Open 返回原生客户端,正常关闭错误由应用首次接收并分类记录。 - 审计插件由应用通过 database.Options.Plugins 显式安装。基础库没有审计 Model、表名和后台身份语义。 - 库保留原生 GORM 方言扩展点;SQLite 用于本地回归,MySQL 的真实连接、方言和项目审计仍需集成环境验证。 +## P1 能力补齐后的兼容说明 + +- 字段约束失败仍返回 HTTP 400,但新增 data.fields 安全提示,message 为 Validation failed;格式绑定错误仍使用通用安全提示。 +- 新增 RequestTimeoutMS 普通 Controller 合作式预算,默认 30000 毫秒;需要保留无预算行为时显式设零。max-exec-time 按秒覆盖,0 禁用,不等同于旧缓冲响应超时中间件。原生 Handle/SSE 保持显式截止方式。 +- 新增 RegisterHealth 与 SetReady,未显式完成就绪装配前 ready 返回 503,依赖检查复用原生池。 +- Context 校验入口为 Form.ValidateContext;旧 Validate 保留供无请求场景兼容。完整装配示例和约束统一见接入指南。 + ## 出站客户端接入边界 新增 httpclient 的 API 不与旧 network/httpclient/define.Response 兼容。先接入无业务码解析的普通调用,再按供应商适配:保留原始 HTTP 状态及字节,由应用映射旧 Response、成功码和任务失败信息。任务提交、查询、搜索和下载不能仅替换 import 路径。 diff --git a/examples/application/config.yml b/examples/application/config.yml new file mode 100644 index 0000000..340b364 --- /dev/null +++ b/examples/application/config.yml @@ -0,0 +1,21 @@ +address: 127.0.0.1:8080 +log_directory: ./logs/application +http: + service: application-example + request_timeout_ms: 30000 +outbound: + timeout_ms: 30000 + connect_timeout_ms: 5000 + max_response_bytes: 8388608 +# 可选依赖:配置后必须初始化成功;凭据由部署环境注入。 +# database: +# name: primary +# host: 127.0.0.1 +# port: 3306 +# username: ${DATABASE_USERNAME} +# password: ${DATABASE_PASSWORD} +# database: ${DATABASE_NAME} +# redis: +# name: cache +# address: 127.0.0.1:6379 +# password: ${REDIS_PASSWORD} diff --git a/examples/application/main.go b/examples/application/main.go new file mode 100644 index 0000000..cf12364 --- /dev/null +++ b/examples/application/main.go @@ -0,0 +1,188 @@ +// Command application 展示配置、日志、连接、出站客户端、健康检查和退出的完整装配。 +package main + +import ( + "context" + "errors" + "flag" + "net" + "os" + "os/signal" + "syscall" + "time" + + "git.zhangdeman.cn/github/ginframework/config" + "git.zhangdeman.cn/github/ginframework/database" + "git.zhangdeman.cn/github/ginframework/fault" + framework "git.zhangdeman.cn/github/ginframework/http" + "git.zhangdeman.cn/github/ginframework/httpclient" + "git.zhangdeman.cn/github/ginframework/logger" + cache "git.zhangdeman.cn/github/ginframework/redis" + "github.com/gin-gonic/gin" + redisclient "github.com/redis/go-redis/v9" +) + +const ( + codeAddress = 990101 + codeListen = 990102 + codeRedisClose = 990103 +) + +type applicationConfig struct { + Address string `json:"address" yaml:"address" dc:"服务监听地址,包含端口"` + LogDirectory string `json:"log_directory" yaml:"log_directory" dc:"本应用拥有的日志目录"` + HTTP framework.Config `json:"http" yaml:"http" dc:"HTTP 数据配置"` + Database *database.Config `json:"database,omitempty" yaml:"database" dc:"可选数据库,配置后必须初始化成功"` + Redis *cache.Config `json:"redis,omitempty" yaml:"redis" dc:"可选 Redis,配置后必须初始化成功"` + Outbound httpclient.Config `json:"outbound" yaml:"outbound" dc:"应用复用的出站客户端策略"` +} + +type resources struct { + database *database.Connection `dc:"尚未对业务发布的数据库连接"` + redis *redisclient.Client `dc:"尚未对业务发布的 Redis 客户端"` + outbound *httpclient.Client `dc:"应用复用并拥有空闲连接池的出站客户端"` +} + +type pingForm struct { + framework.Meta `path:"/ping" method:"GET" summary:"完整装配示例" tag:"example" dc:"路由声明"` +} + +type pingOutput struct { + Status string `json:"status" dc:"示例处理结果"` +} + +type example struct{} + +// Ping 返回普通请求结果,基础依赖已经由应用装配完成。 +// 入参:ctx 为已建立预算的请求,input 为完成校验的 Form。 +// 返回:公开结果,无业务错误时返回 nil。 +func (*example) Ping(ctx *gin.Context, input *pingForm) (*pingOutput, error) { + return &pingOutput{Status: "ok"}, nil +} + +// main 加载显式配置并把进程信号转换为取消上下文。 +func main() { + path := flag.String("config", "examples/application/config.yml", "应用配置路径") + flag.Parse() + var ( + cfg applicationConfig + ) + if err := config.Load(*path, &cfg, config.Options{}); err != nil { + os.Exit(1) + } + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, cfg); err != nil { + // 装配和清理错误均在本示例或组件源头记录,入口只设置退出状态。 + os.Exit(1) + } +} + +// run 只在本函数中创建和连接依赖,失败逆序回收,退出先排空请求。 +// 入参:ctx 为进程取消上下文,cfg 为完成 YAML 解析的应用配置。 +// 返回:装配、监听、排空或资源回收失败时保留完整错误链。 +func run(ctx context.Context, cfg applicationConfig) (err error) { + if _, _, err = net.SplitHostPort(cfg.Address); err != nil { + classified := fault.New(codeAddress, "validate application listen address failed", err) + logger.RecordErrorContext(ctx, "validate application listen address failed", classified) + return classified + } + instance, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: cfg.LogDirectory, UseJSON: true, LogLevel: "info"}) + if err != nil { + return err + } + pending := &resources{} + // 释放时仍有可用日志;已成功返回的资源由当前装配根负责。 + defer func() { err = errors.Join(err, pending.close(), logger.CloseOutputs()) }() + if cfg.Database != nil { + if pending.database, err = database.Open(ctx, *cfg.Database, database.Options{Logger: instance}); err != nil { + return err + } + } + if cfg.Redis != nil { + if pending.redis, err = cache.Open(ctx, *cfg.Redis, instance); err != nil { + return err + } + } + if pending.outbound, err = httpclient.New(cfg.Outbound, httpclient.Options{Logger: instance}); err != nil { + return err + } + server, err := framework.NewServer(cfg.HTTP, framework.Options{AccessLogger: instance}) + if err != nil { + return err + } + // 无论注册、监听还是 Serve 提前失败,返回前均完成请求排空。 + defer func() { server.SetReady(false); err = errors.Join(err, server.Shutdown(context.Background())) }() + if err = server.RegisterHealth("/_health", framework.HealthOptions{Checks: pending.checks()}); err != nil { + return err + } + if err = server.Group("/example", nil, &example{}); err != nil { + return err + } + listener, err := net.Listen("tcp", cfg.Address) + if err != nil { + classified := fault.New(codeListen, "listen application example failed", err) + logger.RecordErrorContext(ctx, "listen application example failed", classified) + return classified + } + defer listener.Close() + // 到这里全部配置的依赖已成功,才发布可被就绪探针观察到的服务。 + server.SetReady(true) + done := make(chan error, 1) + go func() { done <- server.Serve(listener) }() + select { + case err = <-done: + return err + case <-ctx.Done(): + server.SetReady(false) + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return errors.Join(server.Shutdown(shutdown), <-done) + } +} + +// checks 构建固定的依赖探测列表,不创建第二套连接。 +// 返回:只引用本装配根实际启用资源的检查函数。 +func (r *resources) checks() []framework.ReadinessCheck { + var ( + checks []framework.ReadinessCheck + ) + if r.database != nil { + checks = append(checks, framework.ReadinessCheck{Name: "database", Check: func(ctx context.Context) error { + pool, err := r.database.Session(ctx).DB() + if err != nil { + return err + } + return pool.PingContext(ctx) + }}) + } + if r.redis != nil { + checks = append(checks, framework.ReadinessCheck{Name: "redis", Check: func(ctx context.Context) error { return r.redis.Ping(ctx).Err() }}) + } + return checks +} + +// close 逆序释放本次装配创建的资源,不包含仍在途的业务处理。 +// 返回:全部关闭结果合并的原因链,每个对象均会尝试回收。 +func (r *resources) close() error { + var ( + result []error + ) + if r.outbound != nil { + r.outbound.CloseIdleConnections() + r.outbound = nil + } + if r.redis != nil { + if err := r.redis.Close(); err != nil { + classified := fault.New(codeRedisClose, "close application Redis failed", err) + logger.RecordError("close application Redis failed", classified) + result = append(result, classified) + } + r.redis = nil + } + if r.database != nil { + result = append(result, r.database.Close()) + r.database = nil + } + return errors.Join(result...) +} diff --git a/examples/application/main_test.go b/examples/application/main_test.go new file mode 100644 index 0000000..62b40a5 --- /dev/null +++ b/examples/application/main_test.go @@ -0,0 +1,108 @@ +package main + +import ( + "context" + "net" + "net/http" + "path/filepath" + "testing" + "time" + + "git.zhangdeman.cn/github/ginframework/database" + "git.zhangdeman.cn/github/ginframework/httpclient" + "git.zhangdeman.cn/github/ginframework/logger" + cache "git.zhangdeman.cn/github/ginframework/redis" + redisclient "github.com/redis/go-redis/v9" + "gorm.io/driver/sqlite" +) + +func TestConfiguredDependencyFailureReleasesLogging(t *testing.T) { + cfg := applicationConfig{Address: "127.0.0.1:0", LogDirectory: t.TempDir(), Redis: &cache.Config{}} + if err := run(context.Background(), cfg); err == nil { + t.Fatal("configured Redis failure was silently ignored") + } + if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: t.TempDir()}); err != nil { + t.Fatal("startup failure leaked global logs", err) + } + if err := logger.CloseOutputs(); err != nil { + t.Fatal(err) + } +} + +func TestPartialResourceCleanupClosesNativePools(t *testing.T) { + connection, err := database.Open(context.Background(), database.Config{}, database.Options{Dialector: sqlite.Open(":memory:")}) + if err != nil { + t.Fatal(err) + } + pool, err := connection.Session(context.Background()).DB() + if err != nil { + t.Fatal(err) + } + redis := redisclient.NewClient(&redisclient.Options{Network: "unix", Addr: filepath.Join(t.TempDir(), "unused.sock")}) + outbound, err := httpclient.New(httpclient.Config{}, httpclient.Options{}) + if err != nil { + t.Fatal(err) + } + pending := &resources{database: connection, redis: redis, outbound: outbound} + if err = pending.close(); err != nil { + t.Fatal(err) + } + if pool.PingContext(context.Background()) == nil || redis.Ping(context.Background()).Err() == nil { + t.Fatal("partial resources remained open") + } + if pending.database != nil || pending.redis != nil || pending.outbound != nil { + t.Fatal("closed handles still published") + } +} + +func TestApplicationReadinessAndSignalStyleShutdown(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + address := listener.Addr().String() + listener.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + result := make(chan error, 1) + go func() { result <- run(ctx, applicationConfig{Address: address, LogDirectory: t.TempDir()}) }() + client := &http.Client{Timeout: 200 * time.Millisecond} + ready := false + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + response, err := client.Get("http://" + address + "/_health/ready") + if err == nil { + response.Body.Close() + if response.StatusCode == 200 { + ready = true + break + } + } + select { + case err := <-result: + t.Fatalf("application exited before ready: %v", err) + default: + } + time.Sleep(10 * time.Millisecond) + } + if !ready { + cancel() + <-result + t.Fatal("application never became ready") + } + cancel() + select { + case err = <-result: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("application failed to drain") + } + if _, err = logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: t.TempDir()}); err != nil { + t.Fatal("shutdown leaked logs", err) + } + if err = logger.CloseOutputs(); err != nil { + t.Fatal(err) + } +} diff --git a/http/budget.go b/http/budget.go new file mode 100644 index 0000000..8619c30 --- /dev/null +++ b/http/budget.go @@ -0,0 +1,33 @@ +package http + +import ( + "context" + "errors" + "net/http" + + failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "github.com/gin-gonic/gin" +) + +// finishCanceled 在合作式预算结束后统一返回超时响应,保留已分类错误的日志语义。 +// 入参:ctx 为当前请求,cause 为已接收的下层错误,允许 nil。 +// 返回:上下文结束并应停止当前流程时为 true;客户端取消时不继续写响应。 +func (s *Server) finishCanceled(ctx *gin.Context, cause error) bool { + err := ctx.Request.Context().Err() + if err == nil { + return false + } + if cause == nil { + cause = err + } + code, summary := codeRequestCancelled, "HTTP request cancelled" + if errors.Is(err, context.DeadlineExceeded) { + code, summary = codeRequestTimeout, "HTTP request budget exceeded" + } + classified := failure.WrapContext(ctx.Request.Context(), code, summary, cause) + if errors.Is(err, context.DeadlineExceeded) { + s.writeResult(ctx, nil, classified, http.StatusGatewayTimeout) + } + ctx.Abort() + return true +} diff --git a/http/context_flow_test.go b/http/context_flow_test.go new file mode 100644 index 0000000..cef45af --- /dev/null +++ b/http/context_flow_test.go @@ -0,0 +1,161 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "git.zhangdeman.cn/github/ginframework/database" + "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/github/ginframework/httpclient" + "git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver" + "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/github/ginframework/redis/commandlog" + "github.com/gin-gonic/gin" + redisclient "github.com/redis/go-redis/v9" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" + "gorm.io/driver/sqlite" +) + +type flowTransport func(*http.Request) (*http.Response, error) + +func (f flowTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +type flowForm struct { + Meta `path:"/context-flow" method:"GET"` + Bad bool `form:"bad"` +} +type flowController struct { + database *database.Connection + redis *redisclient.Client + outbound *httpclient.Client +} + +func (c *flowController) Run(ctx *gin.Context, input *flowForm) (*exampleOutput, error) { + parent := ctx.Request.Context() + if err := c.database.Session(parent).Exec("SELECT 1").Error; err != nil { + return nil, err + } + if err := c.redis.Ping(parent).Err(); err != nil { + return nil, err + } + target := "https://example.test/ok" + if input.Bad { + target = "https://example.test/bad" + } + response, err := c.outbound.Send(parent, httpclient.Request{URL: target}) + if err != nil { + return nil, err + } + var ( + output exampleOutput + ) + if err = response.DecodeJSON(&output); err != nil { + return nil, err + } + return &output, nil +} + +func TestHTTPDatabaseRedisOutboundKeepOneDiagnosticSnapshot(t *testing.T) { + directory := t.TempDir() + if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: directory, UseJSON: true}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = logger.CloseOutputs() }) + sqlCore, sqlLogs := observer.New(zap.InfoLevel) + connection, err := database.Open(context.Background(), database.Config{Name: "test"}, database.Options{Dialector: sqlite.Open(":memory:"), Logger: zap.New(sqlCore)}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := connection.Close(); err != nil { + t.Error(err) + } + }) + redis := redisserver.New(t, 3) + redisCore, redisLogs := observer.New(zap.InfoLevel) + redis.AddHook(commandlog.New(zap.New(redisCore), "test")) + outboundCore, outboundLogs := observer.New(zap.InfoLevel) + client, err := httpclient.New(httpclient.Config{}, httpclient.Options{Logger: zap.New(outboundCore), Transport: flowTransport(func(r *http.Request) (*http.Response, error) { + if diagnostic.From(r.Context()).TraceID == "" { + return nil, errors.New("outbound context lost") + } + if _, ok := r.Context().Deadline(); !ok { + return nil, errors.New("outbound budget lost") + } + body := `{"name":"ok"}` + if r.URL.Path == "/bad" { + body = `{"private-token":` + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil + })}) + if err != nil { + t.Fatal(err) + } + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.Group("", nil, &flowController{database: connection, redis: redis, outbound: client}); err != nil { + t.Fatal(err) + } + var ( + traces []string + ) + for _, bad := range []bool{false, true} { + path := "/context-flow" + if bad { + path += "?bad=true" + } + recorder := httptest.NewRecorder() + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) + expected := 200 + if bad { + expected = 500 + } + if recorder.Code != expected { + t.Fatalf("flow status=%d: %s", recorder.Code, recorder.Body.String()) + } + traces = append(traces, recorder.Header().Get("X-Request-ID")) + } + for _, trace := range traces { + if trace == "" { + t.Fatal("missing HTTP trace") + } + for name, logs := range map[string]*observer.ObservedLogs{"sql": sqlLogs, "redis": redisLogs, "outbound": outboundLogs} { + found := false + for _, entry := range logs.All() { + raw, _ := json.Marshal(entry.ContextMap()) + if strings.Contains(string(raw), trace) { + found = true + break + } + } + if !found { + t.Fatalf("%s lost HTTP diagnostic snapshot %s", name, trace) + } + } + } + if err = logger.CloseOutputs(); err != nil { + t.Fatal(err) + } + paths, _ := filepath.Glob(filepath.Join(directory, "*")) + if len(paths) != 1 { + t.Fatal("source error log missing") + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + t.Fatal(err) + } + if strings.Count(strings.TrimSpace(string(raw)), "\n") != 0 || !strings.Contains(string(raw), traces[1]) || strings.Contains(string(raw), "private-token") { + t.Fatalf("outbound decode error lost context or logged twice: %s", raw) + } +} diff --git a/http/health.go b/http/health.go new file mode 100644 index 0000000..0391f58 --- /dev/null +++ b/http/health.go @@ -0,0 +1,103 @@ +package http + +import ( + "context" + "errors" + "net/http" + "strings" + "time" + + failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "github.com/gin-gonic/gin" +) + +// ReadinessCheck 是应用声明的依赖探测,不暴露驱动错误到健康响应。 +type ReadinessCheck struct { + Name string `json:"name" dc:"安全的依赖名称,不包含连接地址或凭据"` + Check func(context.Context) error `json:"-" dc:"遵守传入上下文的探测函数,不负责创建连接"` +} + +// HealthOptions 描述固定的启动期探测清单。 +type HealthOptions struct { + TimeoutMS int64 `json:"timeout_ms" dc:"一次就绪检查的总预算毫秒,缺省 1000"` + Checks []ReadinessCheck `json:"-" dc:"应用已创建资源的探测列表,注册时复制"` +} + +type checkResult struct { + Name string `json:"name" dc:"应用声明的安全依赖名称"` + Ready bool `json:"ready" dc:"依赖是否通过检查,不携带原始原因"` +} + +type healthResult struct { + Status string `json:"status" dc:"ok 或 not_ready"` + Checks []checkResult `json:"checks,omitempty" dc:"就绪探测结果,不输出连接信息"` +} + +// RegisterHealth 批次注册 GET {prefix}/live 和 GET {prefix}/ready。 +// 入参:prefix 为完整路径前缀,空值使用 /_health;options 为探测配置。 +// 返回:配置、路由冲突或注册已冻结时返回错误,不部分注册。 +// 隐式逻辑:就绪初始为 false,应用完成全部装配后显式调用 SetReady(true)。 +func (s *Server) RegisterHealth(prefix string, options HealthOptions) error { + if prefix == "" { + prefix = "/_health" + } + prefix = strings.TrimRight(prefix, "/") + if !strings.HasPrefix(prefix, "/") || strings.ContainsAny(prefix, ":*?#") || options.TimeoutMS < 0 || options.TimeoutMS > int64((1<<63-1)/time.Millisecond) { + return failure.Wrap(codeHealthConfig, "validate health endpoint configuration failed", errors.New("invalid health prefix or probe budget")) + } + if options.TimeoutMS == 0 { + options.TimeoutMS = 1000 + } + options.Checks = append([]ReadinessCheck(nil), options.Checks...) + names := make(map[string]bool, len(options.Checks)) + for _, check := range options.Checks { + if strings.TrimSpace(check.Name) == "" || check.Check == nil || names[check.Name] { + return failure.Wrap(codeHealthConfig, "validate readiness check configuration failed", errors.New("check names and callbacks must be unique and non-empty")) + } + names[check.Name] = true + } + return s.commit([]route{ + {meta: Metadata{Method: http.MethodGet, Path: prefix + "/live", Summary: "Process liveness", Tag: "health"}, handlers: []gin.HandlerFunc{func(ctx *gin.Context) { ctx.JSON(http.StatusOK, healthResult{Status: "ok"}) }}}, + {meta: Metadata{Method: http.MethodGet, Path: prefix + "/ready", Summary: "Service readiness", Tag: "health"}, handlers: []gin.HandlerFunc{s.readiness(options)}}, + }) +} + +// SetReady 设置应用装配/排空阶段的就绪信号,不代替依赖探测。 +// 入参:ready 为应用是否允许接收业务流量;停止时框架自动置 false。 +func (s *Server) SetReady(ready bool) { s.ready.Store(ready) } + +// readiness 创建使用固定探测快照的处理器,不建立后台任务或动态注册表。 +// 入参:options 为已经校验的检查清单和总预算。 +// 返回:不泄露检查原始错误的 Gin Handler;回调必须响应取消。 +func (s *Server) readiness(options HealthOptions) gin.HandlerFunc { + return func(ctx *gin.Context) { + if !s.ready.Load() { + ctx.JSON(http.StatusServiceUnavailable, healthResult{Status: "not_ready"}) + return + } + probe, cancel := context.WithTimeout(ctx.Request.Context(), time.Duration(options.TimeoutMS)*time.Millisecond) + defer cancel() + result := healthResult{Status: "ok", Checks: make([]checkResult, 0, len(options.Checks))} + for _, check := range options.Checks { + err := probe.Err() + if err == nil { + err = check.Check(probe) + } + if err == nil { + err = probe.Err() + } + passed := err == nil + if !passed { + _ = failure.WrapContext(probe, codeReadinessCheck, "check service readiness failed", err) + result.Status = "not_ready" + } + result.Checks = append(result.Checks, checkResult{Name: check.Name, Ready: passed}) + } + status := http.StatusOK + if !s.ready.Load() || result.Status != "ok" { + status = http.StatusServiceUnavailable + result.Status = "not_ready" + } + ctx.JSON(status, result) + } +} diff --git a/http/p1_test.go b/http/p1_test.go new file mode 100644 index 0000000..f8ba5b7 --- /dev/null +++ b/http/p1_test.go @@ -0,0 +1,277 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/github/ginframework/http/request" + "git.zhangdeman.cn/github/ginframework/logger" + "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" +) + +type profileInput struct { + Email string `json:"email" binding:"required,email" err:"Enter a valid email address"` + Secret string `json:"secret" binding:"oneof=allowed"` +} +type validationForm struct { + Meta `path:"/validate" method:"POST"` + Profile profileInput `json:"profile" binding:"required"` + Items []profileInput `json:"items" binding:"dive"` + Attributes map[string]profileInput `json:"attributes" binding:"dive"` +} +type validationController struct{} + +func (*validationController) Validate(*gin.Context, *validationForm) (*exampleOutput, error) { + return &exampleOutput{}, nil +} + +func TestFieldErrorsArePublicSafeAndKeepNativeCause(t *testing.T) { + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.Group("", nil, &validationController{}); err != nil { + t.Fatal(err) + } + body := `{"profile":{"email":"private-invalid-email","secret":"private-token"},"items":[{"email":"bad","secret":"allowed"}],"attributes":{"private-map-key":{"email":"bad","secret":"allowed"}}}` + recorder := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/validate", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + server.Handler().ServeHTTP(recorder, req) + if recorder.Code != 400 { + t.Fatalf("status=%d %s", recorder.Code, recorder.Body.String()) + } + var ( + output struct { + Data request.ValidationDetails `json:"data"` + } + ) + if err = json.Unmarshal(recorder.Body.Bytes(), &output); err != nil { + t.Fatal(err) + } + fields := map[string]request.FieldError{} + for _, field := range output.Data.Fields { + fields[field.Field] = field + } + if fields["profile.email"].Rule != "email" || fields["profile.email"].Message != "Enter a valid email address" || fields["items[].email"].Rule != "email" || fields["attributes[].email"].Rule != "email" { + t.Fatalf("field names lost: %+v", fields) + } + for _, hidden := range []string{"private-invalid-email", "private-token", "private-map-key", "oneof=allowed", "validationForm"} { + if strings.Contains(recorder.Body.String(), hidden) { + t.Fatalf("validation leaked %s", hidden) + } + } + var ( + value validationForm + ) + cause := request.Form.ValidateContext(context.Background(), &value) + var ( + native validator.ValidationErrors + ) + if !errors.As(cause, &native) { + t.Fatalf("native validator cause lost: %v", cause) + } +} + +func TestBindingFailureLogsTrustedContextOnce(t *testing.T) { + directory := t.TempDir() + if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: directory, UseJSON: true}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = logger.CloseOutputs() }) + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.Group("", nil, &validationController{}); err != nil { + t.Fatal(err) + } + recorder := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/validate", strings.NewReader(`{"private-token":`)) + req.Header.Set("Content-Type", "application/json") + server.Handler().ServeHTTP(recorder, req) + trace := recorder.Header().Get("X-Request-ID") + if err = logger.CloseOutputs(); err != nil { + t.Fatal(err) + } + paths, _ := filepath.Glob(filepath.Join(directory, "*")) + if len(paths) != 1 { + t.Fatal("log missing") + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(raw)), "\n") + if len(lines) != 1 || trace == "" { + t.Fatalf("duplicate or missing error log: %s", raw) + } + var ( + entry map[string]any + ) + if err = json.Unmarshal([]byte(lines[0]), &entry); err != nil { + t.Fatal(err) + } + if entry["trace_id"] != trace || entry["uri"] != "/validate" || strings.Contains(string(raw), "private-token") { + t.Fatalf("unsafe or missing context: %s", raw) + } +} + +type budgetForm struct { + Meta `path:"/budget" method:"GET"` +} +type disabledBudgetForm struct { + Meta `path:"/unlimited" method:"GET" max-exec-time:"0"` +} +type budgetController struct { + cancelled chan struct{} + release chan struct{} +} + +func (c *budgetController) Wait(ctx *gin.Context, _ *budgetForm) (*exampleOutput, error) { + <-ctx.Request.Context().Done() + close(c.cancelled) + <-c.release + return nil, ctx.Request.Context().Err() +} +func (c *budgetController) Unlimited(ctx *gin.Context, _ *disabledBudgetForm) (*exampleOutput, error) { + if _, exists := ctx.Request.Context().Deadline(); exists { + return nil, errors.New("disabled route still has a deadline") + } + return &exampleOutput{Name: "ok"}, nil +} + +func TestCooperativeBudgetReturns504AfterHandlerStops(t *testing.T) { + budget := int64(20) + server, err := NewServer(Config{RequestTimeoutMS: &budget}, Options{}) + if err != nil { + t.Fatal(err) + } + controller := &budgetController{cancelled: make(chan struct{}), release: make(chan struct{})} + if err = server.Group("", nil, controller); err != nil { + t.Fatal(err) + } + budget = 1 // 构造时必须复制配置,调用方修改不改变当前实例。 + recorder := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + defer close(done) + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/budget", nil)) + }() + select { + case <-controller.cancelled: + case <-time.After(time.Second): + t.Fatal("request budget did not cancel handler") + } + select { + case <-done: + t.Fatal("request returned while handler was still using dependencies") + default: + } + close(controller.release) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("request did not complete") + } + if recorder.Code != 504 || !strings.Contains(recorder.Body.String(), "Gateway Timeout") { + t.Fatalf("unsafe timeout response: %d %s", recorder.Code, recorder.Body.String()) + } + recorder = httptest.NewRecorder() + server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/unlimited", nil)) + if recorder.Code != 200 { + t.Fatalf("route override failed: %s", recorder.Body.String()) + } +} + +func TestHealthReadinessStateAndDependencyFailure(t *testing.T) { + var ( + degraded atomic.Bool + checks atomic.Int32 + ) + server, err := NewServer(Config{}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.RegisterHealth("/_health", HealthOptions{Checks: []ReadinessCheck{{Name: "database", Check: func(ctx context.Context) error { + checks.Add(1) + if diagnostic.From(ctx).TraceID == "" { + t.Error("health context lost") + } + if degraded.Load() { + return errors.New("private-password and address") + } + return nil + }}}}); err != nil { + t.Fatal(err) + } + handler := server.Handler() + probe := func(path string) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) + return recorder + } + if probe("/_health/live").Code != 200 || probe("/_health/ready").Code != 503 || checks.Load() != 0 { + t.Fatal("uninitialized service was ready or liveness depended on DB") + } + server.SetReady(true) + if probe("/_health/ready").Code != 200 { + t.Fatal("initialized service not ready") + } + degraded.Store(true) + response := probe("/_health/ready") + if response.Code != 503 || strings.Contains(response.Body.String(), "private-password") { + t.Fatal("dependency failure was exposed or ignored") + } + if probe("/_health/live").Code != 200 { + t.Fatal("dependency outage incorrectly failed liveness") + } + server.SetReady(false) + if probe("/_health/ready").Code != 503 { + t.Fatal("draining service remained ready") + } + if err = server.RegisterHealth("/late", HealthOptions{}); err == nil { + t.Fatal("health registration was not frozen") + } +} + +func TestReadinessBudgetAndNativeStreamAreSeparate(t *testing.T) { + budget := int64(1) + server, err := NewServer(Config{RequestTimeoutMS: &budget}, Options{}) + if err != nil { + t.Fatal(err) + } + if err = server.RegisterHealth("/_health", HealthOptions{TimeoutMS: 10, Checks: []ReadinessCheck{{Name: "slow", Check: func(ctx context.Context) error { <-ctx.Done(); return ctx.Err() }}}}); err != nil { + t.Fatal(err) + } + if err = server.Handle("GET", "/native", func(ctx *gin.Context) { + if _, exists := ctx.Request.Context().Deadline(); exists { + t.Error("native route received controller budget") + } + ctx.Status(204) + }); err != nil { + t.Fatal(err) + } + server.SetReady(true) + handler := server.Handler() + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/_health/ready", nil)) + if recorder.Code != 503 { + t.Fatal("expired readiness was successful") + } + recorder = httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/native", nil)) + if recorder.Code != 204 { + t.Fatal("native route changed") + } +} diff --git a/http/request/body.go b/http/request/body.go index 00c0603..ffe048e 100644 --- a/http/request/body.go +++ b/http/request/body.go @@ -24,18 +24,18 @@ const ( // 返回:正文副本视图;失败保留读取错误或 http.MaxBytesError 原因链。 func ReadBodyWithLimit(ctx *gin.Context, limit int64) ([]byte, error) { if ctx == nil || ctx.Request == nil { - return nil, fault.Wrap(codeBodyContext, "validate request body context failed", errors.New("request context is missing")) + return nil, fault.WrapContext(contextOf(ctx), codeBodyContext, "validate request body context failed", errors.New("request context is missing")) } if limit <= 0 { limit = DefaultMaxBodyBytes } if limit == 1<<63-1 { - return nil, fault.Wrap(codeBodyLarge, "validate request body limit failed", errors.New("body limit exceeds supported range")) + return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body limit failed", errors.New("body limit exceeds supported range")) } if cached, exists := ctx.Get(bodyCacheKey); exists { body := cached.([]byte) if int64(len(body)) > limit { - return nil, fault.Wrap(codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) + return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) } ctx.Request.Body = io.NopCloser(bytes.NewReader(body)) return body, nil @@ -49,10 +49,10 @@ func ReadBodyWithLimit(ctx *gin.Context, limit int64) ([]byte, error) { _ = original.Close() ctx.Request.Body = io.NopCloser(bytes.NewReader(body)) if err != nil { - return nil, fault.Wrap(codeBodyRead, "read request body failed", err) + return nil, fault.WrapContext(contextOf(ctx), codeBodyRead, "read request body failed", err) } if int64(len(body)) > limit { - return nil, fault.Wrap(codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) + return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) } ctx.Set(bodyCacheKey, body) return body, nil diff --git a/http/request/context.go b/http/request/context.go new file mode 100644 index 0000000..c079867 --- /dev/null +++ b/http/request/context.go @@ -0,0 +1,22 @@ +package request + +import ( + "context" + "github.com/gin-gonic/gin" +) + +// contextOf 在请求适配边界提取标准上下文,不读取客户端身份或诊断头。 +// 入参:ctx 为 Gin 或标准上下文,允许 nil 表示没有请求来源。 +// 返回:保留取消与可信诊断的标准上下文,无来源时使用背景上下文。 +func contextOf(ctx context.Context) context.Context { + if request, ok := ctx.(*gin.Context); ok { + if request != nil && request.Request != nil { + return request.Request.Context() + } + return context.Background() + } + if ctx == nil { + return context.Background() + } + return ctx +} diff --git a/http/request/form.go b/http/request/form.go index 6d9f807..0025828 100644 --- a/http/request/form.go +++ b/http/request/form.go @@ -2,6 +2,7 @@ package request import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -61,13 +62,13 @@ type form struct{} // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) { - defer fault.Capture(&resultError, CodeFormParse1, "parse failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormParse1, "parse failed") if err := formInstance.Bind(ctx, receiver, optionList...); err != nil { return err } defaults.SetDefaults(receiver) - return formInstance.Validate(receiver) + return formInstance.ValidateContext(contextOf(ctx), receiver) } // Bind 按 URI → Query → Body 的顺序绑定请求参数,但不设置默认值或执行校验。 @@ -80,21 +81,21 @@ func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...Pa // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) { - defer fault.Capture(&resultError, CodeFormBind5, "bind failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBind5, "bind failed") if ctx == nil || ctx.Request == nil { - return fault.Wrap(CodeFormBind1, "bind failed", errors.New("invalid gin request context")) + return fault.WrapContext(contextOf(ctx), CodeFormBind1, "bind failed", errors.New("invalid gin request context")) } - if err := validateReceiver(receiver); err != nil { + if err := validateReceiver(contextOf(ctx), receiver); err != nil { return err } option := buildParseOption(optionList...) if err := bindURI(ctx, receiver); err != nil { - return fault.Wrap(CodeFormBind2, "bind failed", fmt.Errorf("bind URI parameters: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBind2, "bind failed", fmt.Errorf("bind URI parameters: %w", err)) } if err := binding.MapFormWithTag(receiver, ctx.Request.URL.Query(), "form"); err != nil { - return fault.Wrap(CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err)) } method := strings.ToUpper(ctx.Request.Method) @@ -105,7 +106,7 @@ func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...Par case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: return formInstance.bindBody(ctx, receiver, option.MaxBodyBytes) default: - return fault.Wrap(CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method)) + return fault.WrapContext(contextOf(ctx), CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method)) } } @@ -116,16 +117,21 @@ func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...Par // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func (*form) Validate(receiver any) (resultError error) { - defer fault.Capture(&resultError, CodeFormValidate1, "validate failed") +func (f *form) Validate(receiver any) error { + return f.ValidateContext(context.Background(), receiver) +} +// ValidateContext 使用可信调用上下文执行一次最终校验,返回安全的字段级错误。 +// 入参:ctx 为标准上下文,receiver 为绑定及可信注入完成的 Form。 +// 返回:字段约束失败返回 ValidationError;错误链与源头日志保留原始校验原因。 +func (*form) ValidateContext(ctx context.Context, receiver any) error { if binding.Validator == nil { return nil } - // 与 RegisterValidation 共用读写锁,保证运行期规则注册不会和请求校验并发修改 validator 缓存。 requestValidatorLock.RLock() defer requestValidatorLock.RUnlock() - return binding.Validator.ValidateStruct(receiver) + err := binding.Validator.ValidateStruct(receiver) + return validationResult(contextOf(ctx), receiver, err) } // bindBody 按请求媒体类型绑定正文,保留正文缓存与大小限制。 @@ -138,7 +144,7 @@ func (*form) Validate(receiver any) (resultError error) { // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes int64) (resultError error) { - defer fault.Capture(&resultError, CodeFormBindBody10, "bind body failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBindBody10, "bind body failed") bodyData, err := ReadBodyWithLimit(ctx, maxBodyBytes) if err != nil { @@ -151,7 +157,7 @@ func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes contentType := ctx.GetHeader("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { - return fault.Wrap(CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err)) } mediaType = strings.ToLower(mediaType) @@ -165,35 +171,35 @@ func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes decoder.DisallowUnknownFields() } if err = decoder.Decode(receiver); err != nil { - return fault.Wrap(CodeFormBindBody2, "bind body failed", fmt.Errorf("decode JSON body: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody2, "bind body failed", fmt.Errorf("decode JSON body: %w", err)) } if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { - return fault.Wrap(CodeFormBindBody3, "bind body failed", errors.New("decode JSON body: multiple JSON values are not allowed")) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody3, "bind body failed", errors.New("decode JSON body: multiple JSON values are not allowed")) } return nil case mediaType == "application/x-www-form-urlencoded": values, parseErr := url.ParseQuery(string(bodyData)) if parseErr != nil { - return fault.Wrap(CodeFormBindBody4, "bind body failed", fmt.Errorf("parse form body: %w", parseErr)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody4, "bind body failed", fmt.Errorf("parse form body: %w", parseErr)) } if err = binding.MapFormWithTag(receiver, values, "form"); err != nil { - return fault.Wrap(CodeFormBindBody5, "bind body failed", fmt.Errorf("bind form body: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody5, "bind body failed", fmt.Errorf("bind form body: %w", err)) } return nil case mediaType == "multipart/form-data": // ReadBodyWithLimit 已恢复 Request.Body,这里可继续交给 net/http 按 boundary 解析。 if err = ctx.Request.ParseMultipartForm(maxBodyBytes); err != nil { - return fault.Wrap(CodeFormBindBody6, "bind body failed", fmt.Errorf("parse multipart body: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody6, "bind body failed", fmt.Errorf("parse multipart body: %w", err)) } if err = binding.MapFormWithTag(receiver, ctx.Request.MultipartForm.Value, "form"); err != nil { - return fault.Wrap(CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %w", err)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %w", err)) } - if err = bindMultipartFiles(receiver, ctx.Request.MultipartForm.File); err != nil { - return fault.Wrap(CodeFormBindBody8, "bind body failed", fmt.Errorf("bind multipart files: %w", err)) + if err = bindMultipartFiles(contextOf(ctx), receiver, ctx.Request.MultipartForm.File); err != nil { + return fault.WrapContext(contextOf(ctx), CodeFormBindBody8, "bind body failed", fmt.Errorf("bind multipart files: %w", err)) } return nil default: - return fault.Wrap(CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType)) + return fault.WrapContext(contextOf(ctx), CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType)) } } @@ -222,19 +228,20 @@ func buildParseOption(optionList ...ParseOptionFunc) ParseOption { // validateReceiver 检查请求绑定目标是否为可写的非空结构体指针。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - receiver:需要写入绑定结果的具体结构体指针。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func validateReceiver(receiver any) (resultError error) { - defer fault.Capture(&resultError, CodeValidateReceiver3, "validate receiver failed") +func validateReceiver(ctx context.Context, receiver any) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeValidateReceiver3, "validate receiver failed") if receiver == nil { - return fault.Wrap(CodeValidateReceiver1, "validate receiver failed", errors.New("request receiver cannot be nil")) + return fault.WrapContext(contextOf(ctx), CodeValidateReceiver1, "validate receiver failed", errors.New("request receiver cannot be nil")) } value := reflect.ValueOf(receiver) if value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Kind() != reflect.Struct { - return fault.Wrap(CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver)) + return fault.WrapContext(contextOf(ctx), CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver)) } return nil } @@ -248,7 +255,7 @@ func validateReceiver(receiver any) (resultError error) { // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 func bindURI(ctx *gin.Context, receiver any) (resultError error) { - defer fault.Capture(&resultError, CodeBindURI1, "bind u r i failed") + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeBindURI1, "bind u r i failed") uriValues := make(map[string][]string, len(ctx.Params)) for _, param := range ctx.Params { @@ -260,34 +267,36 @@ func bindURI(ctx *gin.Context, receiver any) (resultError error) { // bindMultipartFiles 将常见 multipart.FileHeader 字段绑定到请求结构体。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - receiver:需要写入绑定结果的具体结构体指针。 // - files:本次上传解析得到的文件头列表。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func bindMultipartFiles(receiver any, files map[string][]*multipart.FileHeader) (resultError error) { - defer fault.Capture(&resultError, CodeBindMultipartFiles1, "bind multipart files failed") +func bindMultipartFiles(ctx context.Context, receiver any, files map[string][]*multipart.FileHeader) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeBindMultipartFiles1, "bind multipart files failed") - return walkMultipartFields(reflect.ValueOf(receiver), files) + return walkMultipartFields(ctx, reflect.ValueOf(receiver), files) } // walkMultipartFields 递归绑定表单字段及文件,保留嵌入和可选字段语义。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - value:需要按当前方法约定检查或转换的值。 // - files:本次上传解析得到的文件头列表。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func walkMultipartFields(value reflect.Value, files map[string][]*multipart.FileHeader) (resultError error) { - defer fault.Capture(&resultError, CodeWalkMultipartFields2, "walk multipart fields failed") +func walkMultipartFields(ctx context.Context, value reflect.Value, files map[string][]*multipart.FileHeader) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeWalkMultipartFields2, "walk multipart fields failed") if value.Kind() == reflect.Ptr { if value.IsNil() { // 不为仅可能存在的文件字段创建业务对象;非 nil 的嵌套结构仍会继续绑定。 return nil } - return walkMultipartFields(value.Elem(), files) + return walkMultipartFields(ctx, value.Elem(), files) } if value.Kind() != reflect.Struct { return nil @@ -308,13 +317,13 @@ func walkMultipartFields(value reflect.Value, files map[string][]*multipart.File fieldName = structField.Name } if fileList := files[fieldName]; len(fileList) > 0 { - if err := setMultipartFileValue(fieldValue, fileList); err != nil { - return fault.Wrap(CodeWalkMultipartFields1, "walk multipart fields failed", fmt.Errorf("field %s: %w", structField.Name, err)) + if err := setMultipartFileValue(ctx, fieldValue, fileList); err != nil { + return fault.WrapContext(contextOf(ctx), CodeWalkMultipartFields1, "walk multipart fields failed", fmt.Errorf("field %s: %w", structField.Name, err)) } continue } if structField.Anonymous || indirectKind(fieldValue.Type()) == reflect.Struct { - if err := walkMultipartFields(fieldValue, files); err != nil { + if err := walkMultipartFields(ctx, fieldValue, files); err != nil { return err } } @@ -325,16 +334,17 @@ func walkMultipartFields(value reflect.Value, files map[string][]*multipart.File // setMultipartFileValue 按目标字段类型写入单个或多个上传文件。 // // 入参: +// - ctx:当前可信请求或内部调用上下文。 // - fieldValue:需要绑定或检查的可写字段反射值。 // - files:本次上传解析得到的文件头列表。 // // 返回: // - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。 -func setMultipartFileValue(fieldValue reflect.Value, files []*multipart.FileHeader) (resultError error) { - defer fault.Capture(&resultError, CodeSetMultipartFileValue3, "set multipart file value failed") +func setMultipartFileValue(ctx context.Context, fieldValue reflect.Value, files []*multipart.FileHeader) (resultError error) { + defer fault.CaptureContext(contextOf(ctx), &resultError, CodeSetMultipartFileValue3, "set multipart file value failed") if !fieldValue.CanSet() { - return fault.Wrap(CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set")) + return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set")) } switch fieldValue.Type() { case fileHeaderPointerType: @@ -352,7 +362,7 @@ func setMultipartFileValue(fieldValue reflect.Value, files []*multipart.FileHead fieldValue.Set(fileSlice) return nil } - return fault.Wrap(CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type())) + return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type())) } // indirectKind 沿指针类型解析实际字段种类。 diff --git a/http/request/validation.go b/http/request/validation.go new file mode 100644 index 0000000..6a6cb70 --- /dev/null +++ b/http/request/validation.go @@ -0,0 +1,164 @@ +package request + +import ( + "context" + "errors" + "reflect" + "regexp" + "strings" + + failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "github.com/go-playground/validator/v10" +) + +var ( + namespaceIndices = regexp.MustCompile(`\[[^\]]*\]`) +) + +// FieldError 是允许公开的字段约束提示,不包含原始值或校验参数。 +type FieldError struct { + Field string `json:"field" dc:"声明中的公开字段路径,集合下标统一为 []"` + Rule string `json:"rule" dc:"服务端声明的校验规则名,不包含参数或输入值"` + Message string `json:"message" dc:"安全提示,可由字段静态 err 标签指定"` +} + +// ValidationDetails 是统一 400 响应中允许公开的字段错误数据。 +type ValidationDetails struct { + Fields []FieldError `json:"fields" dc:"按校验器顺序排列的安全字段错误"` +} + +// ValidationError 保留原生 validator 原因链及独立的公开提示。 +type ValidationError struct { + Fields []FieldError `json:"fields" dc:"不包含凭据或客户端值的字段级提示"` + cause error `dc:"已在可信调用上下文分类记录的原始错误链"` +} + +// Error 返回安全摘要。 +// 返回:固定的校验失败说明,不输出原始值或内部结构体命名。 +func (e *ValidationError) Error() string { return "request validation failed" } + +// Unwrap 保留 validator 的错误原因。 +// 返回:已记录的内部场景错误,支持继续 errors.As 到原生 ValidationErrors。 +func (e *ValidationError) Unwrap() error { return e.cause } + +// Code 返回所属校验失败场景码。 +// 返回:内部场景码,不作为公开业务错误码。 +func (e *ValidationError) Code() int { return CodeFormValidate1 } + +// validationResult 在校验源头分类并提取静态声明中的安全字段描述。 +// 入参:ctx 为标准上下文,receiver 为校验目标,err 为原生校验结果。 +// 返回:成功时为 nil,字段失败为 ValidationError,其他失败保留原始原因。 +func validationResult(ctx context.Context, receiver any, err error) error { + if err == nil { + return nil + } + classified := failure.WrapContext(ctx, CodeFormValidate1, "validate request fields failed", err) + var ( + fields validator.ValidationErrors + ) + if !errors.As(err, &fields) { + return classified + } + public := make([]FieldError, 0, len(fields)) + for _, field := range fields { + name, message := fieldDescription(reflect.TypeOf(receiver), field.StructNamespace()) + rule := field.Tag() + if message == "" { + message = validationMessage(rule) + } + public = append(public, FieldError{Field: name, Rule: rule, Message: message}) + } + return &ValidationError{Fields: public, cause: classified} +} + +// fieldDescription 只沿静态类型寻找公开名称,屏蔽动态 Map 键及集合下标。 +// 入参:root 为 Form 类型,namespace 为校验器返回的字段路径。 +// 返回:公开字段路径和字段 err 标签;无法映射或显式隐藏时使用 request 与通用提示。 +func fieldDescription(root reflect.Type, namespace string) (string, string) { + for root != nil && root.Kind() == reflect.Ptr { + root = root.Elem() + } + if root == nil || root.Kind() != reflect.Struct { + return "request", "" + } + namespace = strings.TrimPrefix(namespace, root.Name()+".") + parts := strings.Split(namespaceIndices.ReplaceAllString(namespace, "[]"), ".") + var ( + names []string + message string + ) + current := root + for _, part := range parts { + for current.Kind() == reflect.Ptr { + current = current.Elem() + } + if current.Kind() != reflect.Struct { + return "request", "" + } + identifier := strings.SplitN(part, "[", 2)[0] + field, ok := current.FieldByName(identifier) + if !ok || field.PkgPath != "" && !field.Anonymous { + return "request", "" + } + suffix := strings.TrimPrefix(part, identifier) + if strings.ReplaceAll(suffix, "[]", "") != "" { + return "request", "" + } + label := "" + for _, tag := range []string{"json", "form", "uri"} { + candidate := strings.SplitN(field.Tag.Get(tag), ",", 2)[0] + if candidate == "-" { + return "request", "" + } + if candidate != "" { + label = candidate + break + } + } + if label == "" && !field.Anonymous { + label = field.Name + } + if label != "" { + names = append(names, label+suffix) + } + current = field.Type + for i := 0; i < strings.Count(suffix, "[]"); i++ { + for current.Kind() == reflect.Ptr { + current = current.Elem() + } + switch current.Kind() { + case reflect.Map, reflect.Array, reflect.Slice: + current = current.Elem() + default: + return "request", "" + } + } + message = field.Tag.Get("err") + } + if len(names) == 0 { + return "request", "" + } + return strings.Join(names, "."), message +} + +// validationMessage 将常见规则转成不暴露输入或限制参数的安全说明。 +// 入参:rule 为服务端校验规则名。 +// 返回:英文缺省提示,自定义规则返回通用提示。 +func validationMessage(rule string) string { + switch rule { + case "required", "required_if", "required_with", "required_without": + return "This field is required" + case "email": + return "Invalid email address" + case "min", "gte", "gt": + return "Value is below the allowed minimum" + case "max", "lte", "lt": + return "Value exceeds the allowed maximum" + case "len": + return "Invalid length" + case "oneof": + return "Value is not allowed" + default: + return "Invalid value" + } +} diff --git a/http/response.go b/http/response.go index 0456495..80b17bc 100644 --- a/http/response.go +++ b/http/response.go @@ -9,6 +9,7 @@ import ( "git.zhangdeman.cn/github/ginframework/diagnostic" "git.zhangdeman.cn/github/ginframework/fault" + "git.zhangdeman.cn/github/ginframework/http/request" failure "git.zhangdeman.cn/github/ginframework/internal/failure" "git.zhangdeman.cn/github/ginframework/logger" "github.com/gin-gonic/gin" @@ -41,6 +42,11 @@ const ( codeTrustedType = 900424 codeRouteFrozen = 900425 codeRoutePath = 900426 + codeRequestBudget = 900427 + codeRequestTimeout = 900428 + codeHealthConfig = 900429 + codeReadinessCheck = 900430 + codeRequestCancelled = 900431 ) // PublicError 是业务显式允许公开的错误,不包含原始原因文本。 @@ -100,6 +106,13 @@ func (s *Server) writeResult(ctx *gin.Context, data any, err error, status int) } if status != 0 { public = &PublicError{Code: status, Message: http.StatusText(status), Status: status} + var ( + validation *request.ValidationError + ) + if status == http.StatusBadRequest && errors.As(err, &validation) { + public.Message = "Validation failed" + public.Data = request.ValidationDetails{Fields: validation.Fields} + } } result.Code, result.Message, result.Data = public.Code, public.Message, public.Data status = public.Status diff --git a/http/routes.go b/http/routes.go index a2234b2..0c64db0 100644 --- a/http/routes.go +++ b/http/routes.go @@ -84,7 +84,7 @@ func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers if meta.Tag.Get("path") == "" || meta.Tag.Get("method") == "" { return failure.Wrap(codeRouteDeclaration, "validate route declaration failed", errors.New("path and method tags are required")) } - for _, unsupported := range []string{"is-sse", "is-ws", "max-exec-time", "rate-limit", "hook-sync", "output_strict", "no-login"} { + for _, unsupported := range []string{"is-sse", "is-ws", "rate-limit", "hook-sync", "output_strict", "no-login"} { if raw := meta.Tag.Get(unsupported); raw != "" { return failure.Wrap(codeUnsupportedTag, "validate supported route tags failed", fmt.Errorf("tag %s requires an application adapter or a native route", unsupported)) } @@ -108,6 +108,14 @@ func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers // 入参:method 为注册期缓存的方法,formType 为 Form 类型,pointer 为参数形式,meta 为元数据字段。 // 返回:单路由 Handler 或声明错误。 func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, pointer bool, meta reflect.StructField) (gin.HandlerFunc, error) { + budget := time.Duration(*s.config.RequestTimeoutMS) * time.Millisecond + if raw := meta.Tag.Get("max-exec-time"); raw != "" { + seconds, err := strconv.ParseInt(raw, 10, 64) + if err != nil || seconds < 0 || seconds > int64((1<<63-1)/time.Second) { + return nil, failure.Wrap(codeRequestBudget, "validate route request budget failed", errors.New("invalid max-exec-time seconds")) + } + budget = time.Duration(seconds) * time.Second + } limit := request.DefaultMaxBodyBytes if raw := meta.Tag.Get("max-body-bytes"); raw != "" { parsed, err := strconv.ParseInt(raw, 10, 64) @@ -117,8 +125,19 @@ func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, limit = parsed } return func(ctx *gin.Context) { + if budget > 0 { + requestContext, cancel := context.WithTimeout(ctx.Request.Context(), budget) + defer cancel() + ctx.Request = ctx.Request.WithContext(requestContext) + } + if s.finishCanceled(ctx, nil) { + return + } form := reflect.New(formType) if err := request.Form.Bind(ctx, form.Interface(), request.WithMaxBodyBytes(limit)); err != nil { + if s.finishCanceled(ctx, err) { + return + } status := http.StatusBadRequest var ( large *http.MaxBytesError @@ -134,14 +153,23 @@ func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, } defaults.SetDefaults(form.Interface()) if err := s.inject(ctx, form.Elem()); err != nil { + if s.finishCanceled(ctx, err) { + return + } s.writeResult(ctx, nil, err, http.StatusInternalServerError) return } - if err := request.Form.Validate(form.Interface()); err != nil { + if err := request.Form.ValidateContext(ctx.Request.Context(), form.Interface()); err != nil { + if s.finishCanceled(ctx, err) { + return + } s.writeResult(ctx, nil, err, http.StatusBadRequest) return } input := form + if s.finishCanceled(ctx, nil) { + return + } if !pointer { input = form.Elem() } @@ -152,6 +180,9 @@ func (s *Server) controllerHandler(method reflect.Value, formType reflect.Type, if !isNil(result[1]) { err = result[1].Interface().(error) } + if s.finishCanceled(ctx, err) { + return + } s.writeResult(ctx, result[0].Interface(), err, 0) }, nil } @@ -181,7 +212,7 @@ func (s *Server) inject(ctx *gin.Context, form reflect.Value) error { if field.Kind() == reflect.Ptr { if field.IsNil() { if !field.CanSet() { - return failure.Wrap(codeInject, "resolve trusted field failed", errors.New("embedded field is not writable")) + return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", errors.New("embedded field is not writable")) } field.Set(reflect.New(field.Type().Elem())) } @@ -190,19 +221,19 @@ func (s *Server) inject(ctx *gin.Context, form reflect.Value) error { field = field.Field(index) } if !field.CanSet() { - return failure.Wrap(codeInject, "resolve trusted field failed", errors.New("trusted field is not writable")) + return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", errors.New("trusted field is not writable")) } field.SetZero() value, err := s.options.TrustedFields[name](ctx) if err != nil { - return failure.Wrap(codeTrustedRead, "read trusted field failed", err) + return failure.WrapContext(ctx.Request.Context(), codeTrustedRead, "read trusted field failed", err) } if value == nil { continue } source := reflect.ValueOf(value) if !source.Type().AssignableTo(field.Type()) { - return failure.Wrap(codeTrustedType, "assign trusted field failed", errors.New("trusted field type mismatch")) + return failure.WrapContext(ctx.Request.Context(), codeTrustedType, "assign trusted field failed", errors.New("trusted field type mismatch")) } field.Set(source) } diff --git a/http/server.go b/http/server.go index 6519640..6e1d73b 100644 --- a/http/server.go +++ b/http/server.go @@ -7,6 +7,7 @@ import ( "net/http" "sort" "sync" + "sync/atomic" "time" "git.zhangdeman.cn/github/ginframework/diagnostic" @@ -28,6 +29,7 @@ type Config struct { SuccessCode int `json:"success_code" yaml:"success_code" dc:"成功业务码,零为默认"` ReadHeaderTimeoutMS int `json:"read_header_timeout_ms" yaml:"read_header_timeout_ms" dc:"请求头读取超时毫秒,缺省 5000"` TrustedProxies []string `json:"trusted_proxies" yaml:"trusted_proxies" dc:"可信代理名单,缺省不信任转发头"` + RequestTimeoutMS *int64 `json:"request_timeout_ms" yaml:"request_timeout_ms" dc:"普通 Controller 请求合作式预算毫秒,缺省 30000,零禁用;原生 Handle 不自动套用"` } // Options 是调用方显式注入的 HTTP 运行依赖。 @@ -53,12 +55,21 @@ type Server struct { cancel context.CancelFunc `dc:"取消长请求及 SSE 的函数"` routes []route `dc:"启动期保存的不可变路由计划"` trustedFieldNames []string `dc:"启动时排序的可信字段名,避免每个请求重复构建和排序"` + ready atomic.Bool `dc:"应用装配完成的就绪信号,不代替依赖探测"` } // NewServer 创建独立 HTTP 实例,不修改 Gin 全局运行模式。 // 入参:cfg 为数据配置,options 为运行期函数及日志依赖。 // 返回:服务实例;非法代理和超时配置返回内部错误。 func NewServer(cfg Config, options Options) (*Server, error) { + budget := int64(30000) + if cfg.RequestTimeoutMS != nil { + budget = *cfg.RequestTimeoutMS + } + if budget < 0 || budget > int64((1<<63-1)/time.Millisecond) { + return nil, failure.Wrap(codeRequestBudget, "validate HTTP request budget failed", errors.New("invalid request budget")) + } + cfg.RequestTimeoutMS = &budget if cfg.ReadHeaderTimeoutMS < 0 { return nil, failure.Wrap(codeServerConfig, "validate HTTP timeout failed", errors.New("negative header timeout")) } @@ -154,6 +165,7 @@ func (s *Server) Serve(listener net.Listener) error { func (s *Server) Shutdown(ctx context.Context) error { s.lock.Lock() s.stopping = true + s.ready.Store(false) s.frozen = true server := s.server s.cancel() diff --git a/httpclient/request.go b/httpclient/request.go index 1d46650..712b3d5 100644 --- a/httpclient/request.go +++ b/httpclient/request.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "git.zhangdeman.cn/github/ginframework/diagnostic" failure "git.zhangdeman.cn/github/ginframework/internal/failure" ) @@ -28,10 +29,11 @@ type Request struct { // Response 保存有界缓冲结果,不对供应商业务码作推断。 type Response struct { - StatusCode int `json:"status_code" dc:"上游真实 HTTP 状态,非 2xx 也保留正文"` - Header http.Header `json:"-" dc:"上游原生响应头,不参与默认序列化"` - Body []byte `json:"-" dc:"完整响应字节,超限或读取失败时不返回部分正文"` - Duration time.Duration `json:"duration" dc:"从构造后发送到正文读取关闭完成的耗时,纳秒"` + diagnostics diagnostic.Snapshot `dc:"发送时的可信标量快照,不持有请求 Context 或可变对象"` + StatusCode int `json:"status_code" dc:"上游真实 HTTP 状态,非 2xx 也保留正文"` + Header http.Header `json:"-" dc:"上游原生响应头,不参与默认序列化"` + Body []byte `json:"-" dc:"完整响应字节,超限或读取失败时不返回部分正文"` + Duration time.Duration `json:"duration" dc:"从构造后发送到正文读取关闭完成的耗时,纳秒"` } // Build 创建原生请求,保留多值参数和正文类型,不执行网络请求。 @@ -144,17 +146,18 @@ func (c *Client) Send(ctx context.Context, input Request) (result *Response, err if int64(len(body)) > c.maxResponseBytes { return nil, failure.WrapContext(ctx, CodeResponseLimit, "buffer outbound response limit exceeded", ErrResponseTooLarge) } - return &Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: body}, nil + return &Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: body, diagnostics: diagnostic.From(ctx)}, nil } // DecodeJSON 解码单份响应 JSON,保留动态数字精度,不把解析失败当作空数据。 // 入参:target 为 encoding/json 支持的非空接收指针。 // 返回:目标类型不匹配、无效 JSON 或多份 JSON 返回内部错误,原始正文不进入日志。 func (r *Response) DecodeJSON(target any) error { + ctx := diagnostic.With(context.Background(), r.diagnostics) decoder := json.NewDecoder(bytes.NewReader(r.Body)) decoder.UseNumber() if err := decoder.Decode(target); err != nil { - return failure.Wrap(CodeJSONDecode, "decode outbound JSON response failed", err) + return failure.WrapContext(ctx, CodeJSONDecode, "decode outbound JSON response failed", err) } var ( extra any @@ -163,7 +166,7 @@ func (r *Response) DecodeJSON(target any) error { if err == nil { err = errors.New("multiple JSON values in response") } - return failure.Wrap(CodeJSONDocuments, "validate outbound JSON document count failed", err) + return failure.WrapContext(ctx, CodeJSONDocuments, "validate outbound JSON document count failed", err) } return nil } diff --git a/internal/failure/error.go b/internal/failure/error.go index 8502733..10db4e5 100644 --- a/internal/failure/error.go +++ b/internal/failure/error.go @@ -34,3 +34,11 @@ func Capture(target *error, code int, message string) { *target = Wrap(code, message, *target) } } + +// CaptureContext 为命名返回值补充场景并在原调用上下文记录一次。 +// 入参:ctx 为可信标准上下文,target 为命名返回值地址,code 为场景码,message 为安全摘要。 +func CaptureContext(ctx context.Context, target *error, code int, message string) { + if target != nil { + *target = WrapContext(ctx, code, message, *target) + } +} diff --git a/redis/client.go b/redis/client.go index 4c2c7fa..0afcf37 100644 --- a/redis/client.go +++ b/redis/client.go @@ -51,7 +51,7 @@ func Open(ctx context.Context, cfg Config, instance *zap.Logger) (*redisclient.C ctx = context.Background() } if cfg.Address == "" || cfg.DB < 0 || cfg.ProbeTimeoutMS < 0 || cfg.PoolSize < 0 || cfg.MinIdleConns < 0 || cfg.MaxIdleConns < 0 || cfg.MaxActiveConns < 0 || cfg.PoolTimeoutMS < 0 || cfg.ConnMaxIdleTimeMS < 0 || cfg.ConnMaxLifetimeMS < 0 || (cfg.Network != "" && cfg.Network != "tcp" && cfg.Network != "unix") { - return nil, fault.Wrap(CodeConfig, "validate Redis configuration failed", errors.New("invalid Redis target or pool configuration")) + return nil, fault.WrapContext(ctx, CodeConfig, "validate Redis configuration failed", errors.New("invalid Redis target or pool configuration")) } options := &redisclient.Options{ Addr: cfg.Address, Network: cfg.Network, Username: cfg.Username, Password: cfg.Password, DB: cfg.DB, ClientName: cfg.Name, @@ -81,7 +81,7 @@ func Open(ctx context.Context, cfg Config, instance *zap.Logger) (*redisclient.C probe, cancel := context.WithTimeout(ctx, time.Duration(cfg.ProbeTimeoutMS)*time.Millisecond) defer cancel() if err := client.Ping(probe).Err(); err != nil { - return nil, errors.Join(fault.Wrap(CodeProbe, "probe Redis failed", err), fault.Wrap(CodeClose, "close pending Redis client failed", client.Close())) + return nil, errors.Join(fault.WrapContext(ctx, CodeProbe, "probe Redis failed", err), fault.WrapContext(ctx, CodeClose, "close pending Redis client failed", client.Close())) } return client, nil } -- 2.36.6 From e901a1e964fc3c3ebe1e0446269a98616e9098e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 26 Nov 2026 20:45:00 -0800 Subject: [PATCH 2/5] =?UTF-8?q?docs(standards):=20=E6=98=8E=E7=A1=AE?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=88=A4=E7=A9=BA=E4=B8=8E=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E6=96=AD=E8=A8=80=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/standards/technical-specification.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/standards/technical-specification.md b/docs/standards/technical-specification.md index f22cfea..83af055 100644 --- a/docs/standards/technical-specification.md +++ b/docs/standards/technical-specification.md @@ -35,6 +35,7 @@ - 生产代码结构体字段带准确中文 dc 标签;导出字段显式声明 snake_case 的 json 标签,不参与序列化的运行依赖使用 json:"-"。匿名嵌入保留字段展开语义,测试夹具除外。 - 注释和提交描述使用中文;日志消息由调用处传入安全英文摘要,动态信息使用结构化字段。 - nil 的合法语义由契约声明;不重复防御已由构造函数保证的依赖,不以简化为由忽略错误或资源清理。 +- 接口入参允许 nil 且需要类型断言时,必须先判断接口是否为 nil 并处理,再执行类型断言。接口包含具体类型的 nil 指针时不等于 nil,类型断言仍可能成功;若契约允许该指针为 nil,必须在解引用前单独判断,不得用接口的 nil 检查替代具体指针的 nil 检查。 - 关键行为使用具名常量。兼容逻辑注明 target、introduced、owner、removal,不无条件删除仍有效兼容。 ## 4. 配置与安全 -- 2.36.6 From b4a21f53ac0dcf2818db20063c709e2e24f925e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 26 Nov 2026 21:10:02 -0800 Subject: [PATCH 3/5] =?UTF-8?q?feat(http):=20=E5=A2=9E=E5=8A=A0=20OpenAPI?= =?UTF-8?q?=20=E5=A5=91=E7=BA=A6=E7=94=9F=E6=88=90=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从已注册 Controller 的 Form、返回类型及字段声明生成请求、 响应和校验约束,补充显式安全方案与操作级覆盖。 复用 kin-openapi 原生类型与校验,保留合并绑定语义, 为原生路由和无法等价映射的声明提供补充入口。 同步接入指南、迁移边界和可独立运行的契约导出示例。 验证:make verify、make race-check 及实际示例导出通过。 --- README.md | 8 + docs/getting-started.md | 55 +++- docs/integration-optimization-review.md | 2 +- docs/migration.md | 2 +- examples/openapi/main.go | 76 +++++ go.mod | 6 + go.sum | 16 + http/openapi.go | 223 ++++++++++++++ http/openapi_request.go | 196 ++++++++++++ http/openapi_schema.go | 390 ++++++++++++++++++++++++ http/openapi_test.go | 321 +++++++++++++++++++ http/response.go | 10 + http/routes.go | 7 +- 13 files changed, 1304 insertions(+), 8 deletions(-) create mode 100644 examples/openapi/main.go create mode 100644 http/openapi.go create mode 100644 http/openapi_request.go create mode 100644 http/openapi_schema.go create mode 100644 http/openapi_test.go diff --git a/README.md b/README.md index 613433b..673bed7 100644 --- a/README.md +++ b/README.md @@ -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)。 diff --git a/docs/getting-started.md b/docs/getting-started.md index 9ded748..0a1e9e7 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -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` | 出站连接池、请求编码、有界响应、原生流式与安全流水 | 第三方服务适配 | -库不承载业务认证、权限、用户/管理员模型、数据库审计表、缓存 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 配置 diff --git a/docs/integration-optimization-review.md b/docs/integration-optimization-review.md index 2cbd788..7631ff7 100644 --- a/docs/integration-optimization-review.md +++ b/docs/integration-optimization-review.md @@ -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 传输及流事件各有真实差异;复用基础客户端前先验证原契约,不合并为一个供应商大客户端 | diff --git a/docs/migration.md b/docs/migration.md index 4386648..6de41ce 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -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 的真实连接、方言和项目审计仍需集成环境验证。 diff --git a/examples/openapi/main.go b/examples/openapi/main.go new file mode 100644 index 0000000..4516ee0 --- /dev/null +++ b/examples/openapi/main.go @@ -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 +} diff --git a/go.mod b/go.mod index 52e1137..6f24e10 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index d6f79af..e0ddb7b 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/http/openapi.go b/http/openapi.go new file mode 100644 index 0000000..1b05cd9 --- /dev/null +++ b/http/openapi.go @@ -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 +} diff --git a/http/openapi_request.go b/http/openapi_request.go new file mode 100644 index 0000000..34553e3 --- /dev/null +++ b/http/openapi_request.go @@ -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 +} diff --git a/http/openapi_schema.go b/http/openapi_schema.go new file mode 100644 index 0000000..a6043f9 --- /dev/null +++ b/http/openapi_schema.go @@ -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 = © + 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 + } + } +} diff --git a/http/openapi_test.go b/http/openapi_test.go new file mode 100644 index 0000000..33b85ef --- /dev/null +++ b/http/openapi_test.go @@ -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") + } +} diff --git a/http/response.go b/http/response.go index 80b17bc..2b29d38 100644 --- a/http/response.go +++ b/http/response.go @@ -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 是业务显式允许公开的错误,不包含原始原因文本。 diff --git a/http/routes.go b/http/routes.go index 0c64db0..674a50f 100644 --- a/http/routes.go +++ b/http/routes.go @@ -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")}) } } } -- 2.36.6 From 44e21e1322be2fbb3720fb9c1e7b50e7fa9c5432 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 27 Nov 2026 01:54:47 -0800 Subject: [PATCH 4/5] feat: update go mod --- go.mod | 61 ++++++++++++++++++++++++++++---------------------------- go.sum | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 30 deletions(-) diff --git a/go.mod b/go.mod index 6f24e10..2104562 100644 --- a/go.mod +++ b/go.mod @@ -3,15 +3,15 @@ module git.zhangdeman.cn/github/ginframework go 1.27.0 require ( - github.com/getkin/kin-openapi v0.152.0 + github.com/getkin/kin-openapi v0.153.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 + github.com/go-playground/validator/v10 v10.30.6 + github.com/go-sql-driver/mysql v1.10.2 github.com/goccy/go-yaml v1.19.2 github.com/google/uuid v1.6.0 github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible github.com/mcuadros/go-defaults v1.2.0 - github.com/redis/go-redis/v9 v9.23.0 + github.com/redis/go-redis/v9 v9.24.0 go.uber.org/zap v1.28.0 gorm.io/driver/mysql v1.6.0 gorm.io/driver/sqlite v1.6.0 @@ -20,45 +20,46 @@ require ( require ( filippo.io/edwards25519 v1.2.0 // indirect - github.com/bytedance/gopkg v0.1.3 // indirect - github.com/bytedance/sonic v1.15.0 // indirect - github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/bytedance/gopkg v0.1.4 // indirect + github.com/bytedance/sonic v1.15.5 // indirect + github.com/bytedance/sonic/loader v0.5.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - 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 + github.com/cloudwego/base64x v0.1.7 // indirect + github.com/gabriel-vasile/mimetype v1.4.16 // indirect + github.com/gin-contrib/sse v1.2.1 // indirect + github.com/go-openapi/jsonpointer v1.0.3 // indirect + github.com/go-openapi/swag/jsonname v0.29.2 // indirect + github.com/go-playground/locales v0.14.2 // indirect + github.com/go-playground/universal-translator v0.18.2 // indirect + github.com/goccy/go-json v0.12.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/jonboulle/clockwork v0.3.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/cpuid/v2 v2.4.0 // indirect + github.com/klauspost/cpuid/v2 v2.4.2 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/lestrrat-go/strftime v1.2.1 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect 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/oasdiff/yaml v0.1.3 // indirect + github.com/oasdiff/yaml3 v0.0.16 // indirect + github.com/pelletier/go-toml/v2 v2.4.3 // 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/quic-go/quic-go v0.66.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 + github.com/ugorji/go/codec v1.3.2 // indirect + go.mongodb.org/mongo-driver/v2 v2.10.1 // indirect go.uber.org/atomic v1.12.0 // indirect - go.uber.org/multierr v1.10.0 // indirect - golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.58.0 // indirect - golang.org/x/net v0.62.0 // indirect - golang.org/x/sys v0.49.0 // indirect - golang.org/x/text v0.43.0 // indirect - google.golang.org/protobuf v1.36.10 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.yaml.in/yaml/v4 v4.0.0 // indirect + golang.org/x/arch v0.33.0 // indirect + golang.org/x/crypto v0.59.0 // indirect + golang.org/x/net v0.63.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/go.sum b/go.sum index e0ddb7b..b76ef9c 100644 --- a/go.sum +++ b/go.sum @@ -6,14 +6,22 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM= +github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic v1.15.5 h1:gKWTBfYCIQpQHZ7LpwGf9Gj3N88ZN0G/GaB3EQhiGXE= +github.com/bytedance/sonic v1.15.5/go.mod h1:nn7CoK5W+LKbl22XGJrXg6SwzaFAcVs89miqzkqDwOU= github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/bytedance/sonic/loader v0.5.3 h1:ziVGAbXQtLoaot/M6YQxntGkekxz6B/DyuJVwnTbMAA= +github.com/bytedance/sonic/loader v0.5.3/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/cloudwego/base64x v0.1.7 h1:NppS+Fgzg5ovhn4NkUXaDT3x9jldgH5ToMCqzBSi2zI= +github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4X2SQ8aWYg= 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= @@ -21,30 +29,51 @@ github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxK 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/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= +github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= 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/getkin/kin-openapi v0.153.0 h1:Qo4qWW+Pj8o90LUTE6MDyG5TJAtWnfvrcWOBcWg7eBw= +github.com/getkin/kin-openapi v0.153.0/go.mod h1:mEZ6Ip3gyqPDokUsJsttZhv3r46/NeH3tGwrFUMcoSE= 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-contrib/sse v1.2.1 h1:VAN6YEQlc6DbKmGYzSHZ72JWk5fp4gZaDwie4+bXx7s= +github.com/gin-contrib/sse v1.2.1/go.mod h1:9ivB3pROCxcwnwHvAoYaHLwNQMGmzCjgriA04TuNIAc= 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/jsonpointer v1.0.3 h1:iEtrz/inxw+0za5lr10whyxplQdwJruNoQAFA6Sogso= +github.com/go-openapi/jsonpointer v1.0.3/go.mod h1:rf2X/7HDNST8NkSpeV5gTOJeCZXwcIHyVbr5CPiWSDU= 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/swag/jsonname v0.29.2 h1:u5e4IQxc7Yxw1APbtOmfY+Lv4lVZSV1KQiMb/Uj35jc= +github.com/go-openapi/swag/jsonname v0.29.2/go.mod h1:EMHY1EUECld0oRKGSkA6Vmzw138nWoSpavlVBep6msk= 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-openapi/testify/v2 v2.8.1 h1:zk3S6KaDY1iQW91vsOJc25Ql1xm5bhPrZKdnL930bRQ= 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= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= +github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= +github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4= github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ= +github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= +github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/go-sql-driver/mysql v1.10.2 h1:5TRvGvczDohUMOCRA5aCAXgfSZOo/oNDSFD/2RrChS0= +github.com/go-sql-driver/mysql v1.10.2/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI= +github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -62,6 +91,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ= +github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -78,6 +109,8 @@ github.com/lestrrat-go/strftime v1.2.1 h1:LltxP/0ho+7sPY1qiwHQcKK/ksVllY9/8DY3EG github.com/lestrrat-go/strftime v1.2.1/go.mod h1:kI9g6UMJkvbykHIC2Nf7BbQ0tgYbZIoD2mOS0f0T+tg= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mcuadros/go-defaults v1.2.0 h1:FODb8WSf0uGaY8elWJAkoLL0Ri6AlZ1bFlenk56oZtc= @@ -90,10 +123,16 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY 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/yaml v0.1.3 h1:TdwO8e1G1F+bN++LzHj6IWExcuqMjQ1xK8KRYWTffWE= +github.com/oasdiff/yaml v0.1.3/go.mod h1:vxzaFi+b+l+FWC/2NZMm+yD4DzyzwPCwaeLj1x1XfMg= 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/oasdiff/yaml3 v0.0.16 h1:NlDF/1oIOhmOvrEb9eH6Sbuubp3gZNS4A+MKST5/p0Q= +github.com/oasdiff/yaml3 v0.0.16/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/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= +github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -101,8 +140,12 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/quic-go/quic-go v0.66.0 h1:NCsBBGZrI2HZC6aKt4I89T5i4Crt39EYNqkh0w2Wgmg= +github.com/quic-go/quic-go v0.66.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= +github.com/redis/go-redis/v9 v9.24.0 h1:X1AnQHWaSfMeggDQm7UFad1YwJmoZxVm5XkaP0kr6nQ= +github.com/redis/go-redis/v9 v9.24.0/go.mod h1:ted97kpLnB4S2KJkTkw+7GzRjgkFnU909IIrksu+ut4= 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= @@ -122,10 +165,14 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc= +github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.mongodb.org/mongo-driver/v2 v2.10.1 h1:FScYVU+0h/zERnvYemJix3ZDgeU2QGmC8EuXLSWLdf8= +go.mongodb.org/mongo-driver/v2 v2.10.1/go.mod h1:PxPyIAlsI1jkYZvUNfTr++ggyBP+RSaxHYctt6TcZc4= go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -134,23 +181,39 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw= +go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/arch v0.33.0 h1:Xhs4e8nHj/CU/eFFMok2wQG3amA8430Sjdobboa4NrM= +golang.org/x/arch v0.33.0/go.mod h1:yelN722/RE0EdL5KBgAqvVqP++p/dn8sL4UaLD8n8As= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -- 2.36.6 From 52205b42c8223dd5b1099a7e6b4d90151a875dd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 27 Nov 2026 22:58:26 -0800 Subject: [PATCH 5/5] =?UTF-8?q?chore(module):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E4=BB=93=E5=BA=93=E5=9C=B0=E5=9D=80=E5=8F=8A=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- config/load.go | 2 +- config/load_test.go | 2 +- database/connection.go | 4 ++-- database/connection_test.go | 2 +- database/sqllog/logger.go | 4 ++-- docs/getting-started.md | 6 +++--- examples/application/main.go | 14 +++++++------- examples/application/main_test.go | 8 ++++---- examples/minimal/main.go | 4 ++-- examples/openapi/main.go | 6 +++--- go.mod | 2 +- http/budget.go | 2 +- http/context_flow_test.go | 12 ++++++------ http/health.go | 2 +- http/openapi.go | 4 ++-- http/p1_test.go | 6 +++--- http/request/body.go | 2 +- http/request/form.go | 2 +- http/request/init.go | 2 +- http/request/validation.go | 2 +- http/response.go | 10 +++++----- http/routes.go | 4 ++-- http/server.go | 8 ++++---- http/server_test.go | 2 +- httpclient/client.go | 4 ++-- httpclient/client_test.go | 4 ++-- httpclient/example_test.go | 2 +- httpclient/multipart.go | 2 +- httpclient/request.go | 4 ++-- internal/failure/error.go | 4 ++-- logger/output_test.go | 4 ++-- logger/record.go | 4 ++-- logger/storagevalue/value.go | 2 +- redis/client.go | 4 ++-- redis/client_test.go | 4 ++-- redis/commandlog/hook.go | 2 +- redis/commandlog/hook_test.go | 2 +- script/verify/main.go | 2 +- 39 files changed, 81 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 673bed7..d17ec6e 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ 围绕 Gin、GORM/MySQL、Zap、go-redis 和原生 HTTP Client 的独立 Go 基础库。统一请求处理、配置、诊断和资源生命周期,业务认证、审计和供应商策略由消费应用负责。 -- 源码:[git.zhangdeman.cn/github/ginframework](https://git.zhangdeman.cn/github/ginframework) -- Module:`git.zhangdeman.cn/github/ginframework` +- 源码:[git.zhangdeman.cn/zhangdeman/ginframework](https://git.zhangdeman.cn/zhangdeman/ginframework) +- Module:`git.zhangdeman.cn/zhangdeman/ginframework` - 工具链:Go 1.27.0;当前尚未发布版本 tag。 ## 接入使用 @@ -11,7 +11,7 @@ **[接入使用指南](docs/getting-started.md)** 是统一能力清单和使用入口,覆盖安装、最小服务、参数绑定、认证适配、日志、MySQL、Redis、出站 HTTP、SSE 和退出顺序。新增、移除及改变能力须同步该指南,公开包清单纳入 make verify。 ```sh -go get git.zhangdeman.cn/github/ginframework@codex/initial-framework +go get git.zhangdeman.cn/zhangdeman/ginframework@codex/initial-framework ``` 检出本仓库后运行最小 HTTP 示例: diff --git a/config/load.go b/config/load.go index d5b1ff0..adb5067 100644 --- a/config/load.go +++ b/config/load.go @@ -8,7 +8,7 @@ import ( "os" "reflect" - fault "git.zhangdeman.cn/github/ginframework/internal/failure" + fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/goccy/go-yaml" ) diff --git a/config/load_test.go b/config/load_test.go index 3fdd80d..392640d 100644 --- a/config/load_test.go +++ b/config/load_test.go @@ -6,7 +6,7 @@ import ( "path/filepath" "testing" - "git.zhangdeman.cn/github/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" ) func TestStrictEnvironmentAndOptionalValues(t *testing.T) { diff --git a/database/connection.go b/database/connection.go index 48d96f0..a11f6aa 100644 --- a/database/connection.go +++ b/database/connection.go @@ -9,8 +9,8 @@ import ( "strconv" "time" - "git.zhangdeman.cn/github/ginframework/database/sqllog" - fault "git.zhangdeman.cn/github/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/database/sqllog" + fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" mysqlDriver "github.com/go-sql-driver/mysql" "go.uber.org/zap" "gorm.io/driver/mysql" diff --git a/database/connection_test.go b/database/connection_test.go index dd86335..b4780b6 100644 --- a/database/connection_test.go +++ b/database/connection_test.go @@ -5,7 +5,7 @@ import ( "errors" "testing" - "git.zhangdeman.cn/github/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" "gorm.io/driver/sqlite" "gorm.io/gorm" ) diff --git a/database/sqllog/logger.go b/database/sqllog/logger.go index 2fdc616..508f1c0 100644 --- a/database/sqllog/logger.go +++ b/database/sqllog/logger.go @@ -8,9 +8,9 @@ import ( "strings" "time" - "git.zhangdeman.cn/github/ginframework/logger/storagevalue" + "git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue" - "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" "go.uber.org/zap" "gorm.io/gorm" gormLogger "gorm.io/gorm/logger" diff --git a/docs/getting-started.md b/docs/getting-started.md index 0a1e9e7..96d5c44 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -4,12 +4,12 @@ ## 1. 安装与版本 -源码仓库:[github/ginframework](https://git.zhangdeman.cn/github/ginframework)。Go module 与源码地址一致:`git.zhangdeman.cn/github/ginframework`。 +源码仓库:[zhangdeman/ginframework](https://git.zhangdeman.cn/zhangdeman/ginframework)。仓库由 `github/ginframework` 迁移至 `zhangdeman/ginframework`,已有消费项目需同步替换旧 module 依赖及全部导入路径;本库不提供旧路径兼容层。Go module 与源码地址一致:`git.zhangdeman.cn/zhangdeman/ginframework`。 当前需要 Go 1.27.0。库尚未发布版本 tag;首次接入使用初始开发分支,Go 会将分支解析为固定伪版本写入消费项目的 go.mod: ```sh -go get git.zhangdeman.cn/github/ginframework@codex/initial-framework +go get git.zhangdeman.cn/zhangdeman/ginframework@codex/initial-framework go mod tidy ``` @@ -73,7 +73,7 @@ func (*Example) Ping(ctx *gin.Context, form *PingForm) (*PingOutput, error) { } ``` -其中 `framework` 是 `git.zhangdeman.cn/github/ginframework/http` 的导入别名,`gin` 是 `github.com/gin-gonic/gin`。启动函数中装配: +其中 `framework` 是 `git.zhangdeman.cn/zhangdeman/ginframework/http` 的导入别名,`gin` 是 `github.com/gin-gonic/gin`。启动函数中装配: ```go server, err := framework.NewServer(framework.Config{ diff --git a/examples/application/main.go b/examples/application/main.go index cf12364..8f02e03 100644 --- a/examples/application/main.go +++ b/examples/application/main.go @@ -11,13 +11,13 @@ import ( "syscall" "time" - "git.zhangdeman.cn/github/ginframework/config" - "git.zhangdeman.cn/github/ginframework/database" - "git.zhangdeman.cn/github/ginframework/fault" - framework "git.zhangdeman.cn/github/ginframework/http" - "git.zhangdeman.cn/github/ginframework/httpclient" - "git.zhangdeman.cn/github/ginframework/logger" - cache "git.zhangdeman.cn/github/ginframework/redis" + "git.zhangdeman.cn/zhangdeman/ginframework/config" + "git.zhangdeman.cn/zhangdeman/ginframework/database" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" + framework "git.zhangdeman.cn/zhangdeman/ginframework/http" + "git.zhangdeman.cn/zhangdeman/ginframework/httpclient" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" + cache "git.zhangdeman.cn/zhangdeman/ginframework/redis" "github.com/gin-gonic/gin" redisclient "github.com/redis/go-redis/v9" ) diff --git a/examples/application/main_test.go b/examples/application/main_test.go index 62b40a5..309ed7a 100644 --- a/examples/application/main_test.go +++ b/examples/application/main_test.go @@ -8,10 +8,10 @@ import ( "testing" "time" - "git.zhangdeman.cn/github/ginframework/database" - "git.zhangdeman.cn/github/ginframework/httpclient" - "git.zhangdeman.cn/github/ginframework/logger" - cache "git.zhangdeman.cn/github/ginframework/redis" + "git.zhangdeman.cn/zhangdeman/ginframework/database" + "git.zhangdeman.cn/zhangdeman/ginframework/httpclient" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" + cache "git.zhangdeman.cn/zhangdeman/ginframework/redis" redisclient "github.com/redis/go-redis/v9" "gorm.io/driver/sqlite" ) diff --git a/examples/minimal/main.go b/examples/minimal/main.go index 32807c4..dade1e3 100644 --- a/examples/minimal/main.go +++ b/examples/minimal/main.go @@ -9,8 +9,8 @@ import ( "syscall" "time" - framework "git.zhangdeman.cn/github/ginframework/http" - "git.zhangdeman.cn/github/ginframework/logger" + framework "git.zhangdeman.cn/zhangdeman/ginframework/http" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" "github.com/gin-gonic/gin" ) diff --git a/examples/openapi/main.go b/examples/openapi/main.go index 4516ee0..2cde107 100644 --- a/examples/openapi/main.go +++ b/examples/openapi/main.go @@ -6,9 +6,9 @@ import ( "flag" "os" - "git.zhangdeman.cn/github/ginframework/fault" - framework "git.zhangdeman.cn/github/ginframework/http" - "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" + framework "git.zhangdeman.cn/zhangdeman/ginframework/http" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" "github.com/getkin/kin-openapi/openapi3" "github.com/gin-gonic/gin" ) diff --git a/go.mod b/go.mod index 2104562..876d4c0 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module git.zhangdeman.cn/github/ginframework +module git.zhangdeman.cn/zhangdeman/ginframework go 1.27.0 diff --git a/http/budget.go b/http/budget.go index 8619c30..f2a2eb8 100644 --- a/http/budget.go +++ b/http/budget.go @@ -5,7 +5,7 @@ import ( "errors" "net/http" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" ) diff --git a/http/context_flow_test.go b/http/context_flow_test.go index cef45af..d5fbf82 100644 --- a/http/context_flow_test.go +++ b/http/context_flow_test.go @@ -12,12 +12,12 @@ import ( "strings" "testing" - "git.zhangdeman.cn/github/ginframework/database" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/httpclient" - "git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver" - "git.zhangdeman.cn/github/ginframework/logger" - "git.zhangdeman.cn/github/ginframework/redis/commandlog" + "git.zhangdeman.cn/zhangdeman/ginframework/database" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/httpclient" + "git.zhangdeman.cn/zhangdeman/ginframework/internal/testutil/redisserver" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" + "git.zhangdeman.cn/zhangdeman/ginframework/redis/commandlog" "github.com/gin-gonic/gin" redisclient "github.com/redis/go-redis/v9" "go.uber.org/zap" diff --git a/http/health.go b/http/health.go index 0391f58..1a93c37 100644 --- a/http/health.go +++ b/http/health.go @@ -7,7 +7,7 @@ import ( "strings" "time" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" ) diff --git a/http/openapi.go b/http/openapi.go index 1b05cd9..5509341 100644 --- a/http/openapi.go +++ b/http/openapi.go @@ -9,8 +9,8 @@ import ( "reflect" "strings" - "git.zhangdeman.cn/github/ginframework/http/request" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/http/request" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/getkin/kin-openapi/openapi3" ) diff --git a/http/p1_test.go b/http/p1_test.go index f8ba5b7..d96106b 100644 --- a/http/p1_test.go +++ b/http/p1_test.go @@ -12,9 +12,9 @@ import ( "testing" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/http/request" - "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/http/request" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" ) diff --git a/http/request/body.go b/http/request/body.go index ffe048e..3384162 100644 --- a/http/request/body.go +++ b/http/request/body.go @@ -6,7 +6,7 @@ import ( "io" "net/http" - fault "git.zhangdeman.cn/github/ginframework/internal/failure" + fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" ) diff --git a/http/request/form.go b/http/request/form.go index 0025828..3cd2dd9 100644 --- a/http/request/form.go +++ b/http/request/form.go @@ -14,7 +14,7 @@ import ( "reflect" "strings" - fault "git.zhangdeman.cn/github/ginframework/internal/failure" + fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" diff --git a/http/request/init.go b/http/request/init.go index a13d086..022412c 100644 --- a/http/request/init.go +++ b/http/request/init.go @@ -5,7 +5,7 @@ import ( "strings" "sync" - fault "git.zhangdeman.cn/github/ginframework/internal/failure" + fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator/v10" ) diff --git a/http/request/validation.go b/http/request/validation.go index 6a6cb70..88e2e71 100644 --- a/http/request/validation.go +++ b/http/request/validation.go @@ -7,7 +7,7 @@ import ( "regexp" "strings" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/go-playground/validator/v10" ) diff --git a/http/response.go b/http/response.go index 2b29d38..53d4154 100644 --- a/http/response.go +++ b/http/response.go @@ -7,11 +7,11 @@ import ( "net/http" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/fault" - "git.zhangdeman.cn/github/ginframework/http/request" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" - "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/http/request" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" "github.com/gin-gonic/gin" ) diff --git a/http/routes.go b/http/routes.go index 674a50f..c203f06 100644 --- a/http/routes.go +++ b/http/routes.go @@ -11,8 +11,8 @@ import ( "strings" "time" - "git.zhangdeman.cn/github/ginframework/http/request" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/http/request" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" "github.com/mcuadros/go-defaults" ) diff --git a/http/server.go b/http/server.go index 6e1d73b..943e52b 100644 --- a/http/server.go +++ b/http/server.go @@ -10,10 +10,10 @@ import ( "sync/atomic" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/fault" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" - "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" "github.com/gin-gonic/gin" "github.com/google/uuid" "go.uber.org/zap" diff --git a/http/server_test.go b/http/server_test.go index 24ab794..e29cd52 100644 --- a/http/server_test.go +++ b/http/server_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" "github.com/gin-gonic/gin" ) diff --git a/httpclient/client.go b/httpclient/client.go index c6cd798..d396b4e 100644 --- a/httpclient/client.go +++ b/httpclient/client.go @@ -7,8 +7,8 @@ import ( "net/http" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "go.uber.org/zap" ) diff --git a/httpclient/client_test.go b/httpclient/client_test.go index 69a5940..191f6c5 100644 --- a/httpclient/client_test.go +++ b/httpclient/client_test.go @@ -19,8 +19,8 @@ import ( "testing" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" "go.uber.org/zap" "go.uber.org/zap/zaptest/observer" ) diff --git a/httpclient/example_test.go b/httpclient/example_test.go index 3071a73..782b542 100644 --- a/httpclient/example_test.go +++ b/httpclient/example_test.go @@ -6,7 +6,7 @@ import ( "net/http" "net/http/httptest" - "git.zhangdeman.cn/github/ginframework/httpclient" + "git.zhangdeman.cn/zhangdeman/ginframework/httpclient" ) func ExampleClient_Send() { diff --git a/httpclient/multipart.go b/httpclient/multipart.go index a1ed087..197ae05 100644 --- a/httpclient/multipart.go +++ b/httpclient/multipart.go @@ -8,7 +8,7 @@ import ( "sort" "strings" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" ) // File 是已有内存内容的上传文件,不在编码阶段打开文件或启动后台协程。 diff --git a/httpclient/request.go b/httpclient/request.go index 712b3d5..27b77b2 100644 --- a/httpclient/request.go +++ b/httpclient/request.go @@ -11,8 +11,8 @@ import ( "strings" "time" - "git.zhangdeman.cn/github/ginframework/diagnostic" - failure "git.zhangdeman.cn/github/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" ) // Request 描述单次请求,不保存跨请求的可变参数或供应商成功规则。 diff --git a/internal/failure/error.go b/internal/failure/error.go index 10db4e5..c6c6b94 100644 --- a/internal/failure/error.go +++ b/internal/failure/error.go @@ -4,8 +4,8 @@ package failure import ( "context" - "git.zhangdeman.cn/github/ginframework/fault" - "git.zhangdeman.cn/github/ginframework/logger" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/logger" ) // Wrap 在首次接收原始错误时增加场景并记录,已经分类的错误直接传播。 diff --git a/logger/output_test.go b/logger/output_test.go index ce8c791..5d8af10 100644 --- a/logger/output_test.go +++ b/logger/output_test.go @@ -5,8 +5,8 @@ import ( "context" "encoding/json" "errors" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" "os" "path/filepath" "strings" diff --git a/logger/record.go b/logger/record.go index 59ecdd1..b43597e 100644 --- a/logger/record.go +++ b/logger/record.go @@ -6,8 +6,8 @@ import ( "fmt" "os" - "git.zhangdeman.cn/github/ginframework/diagnostic" - "git.zhangdeman.cn/github/ginframework/logger/storagevalue" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) diff --git a/logger/storagevalue/value.go b/logger/storagevalue/value.go index dd76c53..79403ea 100644 --- a/logger/storagevalue/value.go +++ b/logger/storagevalue/value.go @@ -8,7 +8,7 @@ import ( "reflect" "strings" - "git.zhangdeman.cn/github/ginframework/diagnostic" + "git.zhangdeman.cn/zhangdeman/ginframework/diagnostic" "go.uber.org/zap" ) diff --git a/redis/client.go b/redis/client.go index 0afcf37..ce2cfd8 100644 --- a/redis/client.go +++ b/redis/client.go @@ -6,8 +6,8 @@ import ( "errors" "time" - fault "git.zhangdeman.cn/github/ginframework/internal/failure" - "git.zhangdeman.cn/github/ginframework/redis/commandlog" + fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" + "git.zhangdeman.cn/zhangdeman/ginframework/redis/commandlog" redisclient "github.com/redis/go-redis/v9" "go.uber.org/zap" ) diff --git a/redis/client_test.go b/redis/client_test.go index a82746f..bad520b 100644 --- a/redis/client_test.go +++ b/redis/client_test.go @@ -7,8 +7,8 @@ import ( "testing" "time" - "git.zhangdeman.cn/github/ginframework/fault" - "git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver" + "git.zhangdeman.cn/zhangdeman/ginframework/fault" + "git.zhangdeman.cn/zhangdeman/ginframework/internal/testutil/redisserver" ) func TestOpenNativeClientAndProbeFailure(t *testing.T) { diff --git a/redis/commandlog/hook.go b/redis/commandlog/hook.go index 3de66cb..4c0547d 100644 --- a/redis/commandlog/hook.go +++ b/redis/commandlog/hook.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "git.zhangdeman.cn/github/ginframework/logger/storagevalue" + "git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue" "github.com/redis/go-redis/v9" "go.uber.org/zap" diff --git a/redis/commandlog/hook_test.go b/redis/commandlog/hook_test.go index acfad08..32f6a04 100644 --- a/redis/commandlog/hook_test.go +++ b/redis/commandlog/hook_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver" + "git.zhangdeman.cn/zhangdeman/ginframework/internal/testutil/redisserver" "github.com/redis/go-redis/v9" "go.uber.org/zap" diff --git a/script/verify/main.go b/script/verify/main.go index 2f415d1..7025ace 100644 --- a/script/verify/main.go +++ b/script/verify/main.go @@ -41,7 +41,7 @@ func main() { // 入参:formatCheck 决定检查格式,architecture 决定检查生产 import。 // 返回:第一个解析、格式或架构违规,附文件和必要位置。 func run(formatCheck bool, architecture bool) error { - const module = "git.zhangdeman.cn/github/ginframework" + const module = "git.zhangdeman.cn/zhangdeman/ginframework" return filepath.WalkDir(".", func(path string, entry fs.DirEntry, walkErr error) error { if walkErr != nil { return walkErr -- 2.36.6