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 }