From 98c28520ef6fe3a7c16d7b534c87e091e15e9858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sat, 28 Nov 2026 01:23:33 -0800 Subject: [PATCH] =?UTF-8?q?feat(http):=20=E6=94=AF=E6=8C=81=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E9=80=82=E9=85=8D=E5=99=A8=E6=89=B9=E6=AC=A1=E6=8E=A5?= =?UTF-8?q?=E5=85=A5=E5=8E=9F=E7=94=9F=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/getting-started.md | 6 ++++ http/native.go | 70 +++++++++++++++++++++++++++++++++++++++++ http/native_test.go | 44 ++++++++++++++++++++++++++ http/routes.go | 15 ++++----- http/server.go | 1 + 5 files changed, 129 insertions(+), 7 deletions(-) create mode 100644 http/native.go create mode 100644 http/native_test.go diff --git a/docs/getting-started.md b/docs/getting-started.md index 96d5c44..ac1987c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -231,6 +231,12 @@ go run ./examples/openapi -out /tmp/ginframework-openapi.json 文档和 options 中的数据生成后互不共享到 Server,返回后可由调用方继续编辑;继续编辑后应再次执行 `doc.Validate(ctx)`。如需在线展示,可由应用显式注册原生 `/openapi.json` 路由提供预先序列化的字节,并自行配置访问权限;库不打包 UI、不开后台任务、不持有输出文件。现有 Routes、请求绑定、响应及认证行为均保持原契约,新增依赖固定为 kin-openapi v0.152.0。 +### 5.4 原生路由的批次接入 + +已有业务传输适配可用 `HandleBatch(...NativeRoute)` 原子注册。NativeRoute.Metadata 提供最终方法/路径/文档信息,Handlers 是原生 Gin 链,注册时复制;冲突或冻结会拒绝整个批次,不执行应用 Handler。InputType、OutputType 可成对声明为 reflect.Type,仅用于 OpenAPI Schema,框架不重复绑定、注入、调用或套 Controller 预算。缺省响应按 Envelope 推导,SSE 或既有业务响应须通过 OpenAPIOptions.Customize 覆盖。未提供类型则保留原生未推断契约。 + +`Use(...gin.HandlerFunc)` 可在首次 Handler/Serve/Shutdown 前追加全局中间件,并重建全部既有路由链;失败原子回退。`Options.NoRoute` 显式提供应用静态资源回退或特殊 404,未配置仍使用安全 JSON 404。两项均不暴露可绕过冻结的可变 Gin Engine。框架拥有路由校验和 HTTP 生命周期,认证、业务 Hook、响应格式及资源所有权继续由应用负责。 + ## 6. 配置、日志与诊断 ### 6.1 配置 diff --git a/http/native.go b/http/native.go new file mode 100644 index 0000000..0b68a91 --- /dev/null +++ b/http/native.go @@ -0,0 +1,70 @@ +package http + +import ( + "errors" + "reflect" + + failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" + "github.com/gin-gonic/gin" +) + +// NativeRoute 是应用已经完成业务策略装配的原生路由,不再触发 Controller 调用。 +type NativeRoute struct { + Metadata `dc:"最终路径、方法及公开文档元数据"` + Handlers []gin.HandlerFunc `json:"-" dc:"应用装配的中间件和处理器,注册时复制"` + InputType reflect.Type `json:"-" dc:"可选 Form 类型,仅用于契约生成,不参与绑定或执行"` + OutputType reflect.Type `json:"-" dc:"可选公开 DTO 类型,与 InputType 同时提供"` +} + +// HandleBatch 原子注册原生路由,复用框架的路由冲突检查和冻结边界。 +// 入参:routes 为已装配的路由;返回任一配置或冲突错误,失败不部分注册。 +// 隐式逻辑:类型仅作 OpenAPI 声明,默认按 Envelope 推导;特殊响应通过 Customize 覆盖。 +func (s *Server) HandleBatch(routes ...NativeRoute) error { + planned := make([]route, 0, len(routes)) + for _, item := range routes { + if len(item.Handlers) == 0 { + return failure.Wrap(codeRouteHandler, "validate native route handler failed", errors.New("route handler is required")) + } + if (item.InputType == nil) != (item.OutputType == nil) { + return failure.Wrap(codeControllerForm, "validate native route contract failed", errors.New("input and output types must be declared together")) + } + input := item.InputType + if input != nil { + for input.Kind() == reflect.Ptr { + input = input.Elem() + } + if input.Kind() != reflect.Struct { + return failure.Wrap(codeControllerForm, "validate native request contract failed", errors.New("input type must be a struct or struct pointer")) + } + } + planned = append(planned, route{meta: item.Metadata, handlers: append([]gin.HandlerFunc(nil), item.Handlers...), input: input, output: item.OutputType}) + } + return s.commit(planned) +} + +// Use 在启动阶段追加全局中间件,并原子重建既有路由链。 +// 入参:handlers 为明确的应用中间件;返回配置或冻结错误,不改变原引擎。 +func (s *Server) Use(handlers ...gin.HandlerFunc) error { + s.lock.Lock() + defer s.lock.Unlock() + if s.frozen || s.stopping { + return failure.Wrap(codeRouteFrozen, "configure frozen HTTP middleware failed", errors.New("HTTP routes are frozen")) + } + if len(s.options.Middleware)+len(handlers) > 58 { + return failure.Wrap(codeMiddlewareCount, "validate HTTP middleware count failed", errors.New("too many global middleware handlers")) + } + for _, handler := range handlers { + if handler == nil { + return failure.Wrap(codeMiddlewareHandler, "validate HTTP middleware failed", errors.New("nil global middleware")) + } + } + previous := s.options.Middleware + s.options.Middleware = append(append([]gin.HandlerFunc(nil), previous...), handlers...) + engine, err := s.buildEngine(s.routes) + if err != nil { + s.options.Middleware = previous + return err + } + s.engine = engine + return nil +} diff --git a/http/native_test.go b/http/native_test.go new file mode 100644 index 0000000..645d727 --- /dev/null +++ b/http/native_test.go @@ -0,0 +1,44 @@ +package http + +import ( + "net/http/httptest" + "reflect" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestNativeBatchAtomicRegistrationAndMiddlewareFreeze(t *testing.T) { + server, _ := NewServer(Config{}, Options{NoRoute: func(ctx *gin.Context) { ctx.String(404, "application fallback") }}) + ok := func(ctx *gin.Context) { ctx.Status(204) } + if err := server.HandleBatch(NativeRoute{Metadata: Metadata{Method: "GET", Path: "/first"}, Handlers: []gin.HandlerFunc{ok}}, NativeRoute{Metadata: Metadata{Method: "GET", Path: "/first"}, Handlers: []gin.HandlerFunc{ok}}); err == nil { + t.Fatal("duplicate batch accepted") + } + if len(server.Routes()) != 0 { + t.Fatal("failed batch partially registered") + } + if err := server.HandleBatch(NativeRoute{Metadata: Metadata{Method: "GET", Path: "/first"}, Handlers: []gin.HandlerFunc{ok}, InputType: reflect.TypeOf(flowForm{}), OutputType: reflect.TypeOf(exampleOutput{})}); err != nil { + t.Fatal(err) + } + if err := server.Use(func(ctx *gin.Context) { ctx.Header("X-Application", "ready"); ctx.Next() }); err != nil { + t.Fatal(err) + } + doc, err := server.OpenAPI(OpenAPIOptions{Title: "Native", Version: "1"}) + if err != nil || doc.Paths.Value("/first").Get.Responses.Status(200) == nil { + t.Fatal("typed native contract lost", err) + } + handler := server.Handler() + for _, path := range []string{"/first", "/missing"} { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) + if recorder.Header().Get("X-Application") != "ready" { + t.Fatal("late middleware not applied") + } + if path == "/missing" && recorder.Body.String() != "application fallback" { + t.Fatal("application fallback lost") + } + } + if server.Use(ok) == nil || server.Handle("GET", "/late", ok) == nil { + t.Fatal("runtime registration was not frozen") + } +} diff --git a/http/routes.go b/http/routes.go index c203f06..7e6a2b1 100644 --- a/http/routes.go +++ b/http/routes.go @@ -45,10 +45,7 @@ type TrustedField func(ctx *gin.Context) (any, error) // 入参:method 为大写 HTTP 方法,routePath 为完整路径,handlers 为中间件和处理器。 // 返回:路由冲突、配置无效或服务已冻结时返回错误,不部分注册。 func (s *Server) Handle(method string, routePath string, handlers ...gin.HandlerFunc) error { - if len(handlers) == 0 { - return failure.Wrap(codeRouteHandler, "validate native route handler failed", errors.New("route handler is required")) - } - return s.commit([]route{{meta: Metadata{Method: method, Path: routePath}, handlers: append([]gin.HandlerFunc(nil), handlers...)}}) + return s.HandleBatch(NativeRoute{Metadata: Metadata{Method: method, Path: routePath}, Handlers: handlers}) } // Group 解析 Controller 的 Form/Meta 方法并作为一个批次注册。 @@ -277,9 +274,13 @@ func (s *Server) buildEngine(routes []route) (engine *gin.Engine, err error) { } engine.Use(s.initialize) engine.Use(s.options.Middleware...) - engine.NoRoute(func(ctx *gin.Context) { - s.writeResult(ctx, nil, &PublicError{Code: 404, Message: "Not Found", Status: 404}, 0) - }) + if s.options.NoRoute != nil { + engine.NoRoute(s.options.NoRoute) + } else { + engine.NoRoute(func(ctx *gin.Context) { + s.writeResult(ctx, nil, &PublicError{Code: 404, Message: "Not Found", Status: 404}, 0) + }) + } for _, item := range routes { if item.meta.Path == "" || !strings.HasPrefix(item.meta.Path, "/") || item.meta.Method == "" { return nil, failure.Wrap(codeRoutePath, "validate HTTP route path failed", errors.New("method and absolute route path are required")) diff --git a/http/server.go b/http/server.go index 943e52b..15aaff8 100644 --- a/http/server.go +++ b/http/server.go @@ -38,6 +38,7 @@ type Options struct { Middleware []gin.HandlerFunc `json:"-" dc:"业务认证等全局中间件,启动时复制"` ErrorMapper ErrorMapper `json:"-" dc:"业务错误到公开响应的转换函数"` AccessLogger *zap.Logger `json:"-" dc:"访问日志实例,nil 表示关闭"` + NoRoute gin.HandlerFunc `json:"-" dc:"应用可选的未匹配路由处理器,未配置使用安全 404"` } // Server 拥有单个 Gin 引擎及 HTTP 生命周期,不拥有数据库和业务协程。