Verify / verify (push) Canceled after 0s
从已注册 Controller 的 Form、返回类型及字段声明生成请求、 响应和校验约束,补充显式安全方案与操作级覆盖。 复用 kin-openapi 原生类型与校验,保留合并绑定语义, 为原生路由和无法等价映射的声明提供补充入口。 同步接入指南、迁移边界和可独立运行的契约导出示例。 验证:make verify、make race-check 及实际示例导出通过。
324 lines
12 KiB
Go
324 lines
12 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"path"
|
|
"reflect"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.zhangdeman.cn/github/ginframework/http/request"
|
|
failure "git.zhangdeman.cn/github/ginframework/internal/failure"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/mcuadros/go-defaults"
|
|
)
|
|
|
|
// Meta 通过 Form 内嵌字段的 tag 声明路由,Input 不依赖本包。
|
|
type Meta struct{}
|
|
|
|
// Metadata 是路由注册完成后的轻量只读快照,完整契约通过 Server.OpenAPI 生成。
|
|
type Metadata struct {
|
|
Method string `json:"method" dc:"大写 HTTP 方法"`
|
|
Path string `json:"path" dc:"包含分组前缀的最终路径"`
|
|
Summary string `json:"summary" dc:"路由功能描述"`
|
|
Tag string `json:"tag" dc:"路由文档分类"`
|
|
}
|
|
|
|
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 从可信认证上下文读取一个公共字段,不读取客户端原始输入。
|
|
// 入参:ctx 为完成应用认证后的请求上下文。
|
|
// 返回:与字段类型匹配的值,nil 表示清空;错误中止请求。
|
|
type TrustedField func(ctx *gin.Context) (any, error)
|
|
|
|
// Handle 在启动阶段注册原生 Gin 路由,SSE 等流式响应可直接使用。
|
|
// 入参: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...)}})
|
|
}
|
|
|
|
// Group 解析 Controller 的 Form/Meta 方法并作为一个批次注册。
|
|
// 入参:prefix 为分组前缀,middleware 为所属组中间件,controllers 为具体控制器指针。
|
|
// 返回:任一方法签名、路径、tag 或冲突错误都会拒绝整个批次。
|
|
func (s *Server) Group(prefix string, middleware []gin.HandlerFunc, controllers ...any) error {
|
|
var (
|
|
planned []route
|
|
)
|
|
for _, controller := range controllers {
|
|
value := reflect.ValueOf(controller)
|
|
if !value.IsValid() || value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Kind() != reflect.Struct {
|
|
return failure.Wrap(codeControllerInstance, "validate HTTP controller failed", errors.New("controller must be a non-nil struct pointer"))
|
|
}
|
|
for i := 0; i < value.NumMethod(); i++ {
|
|
method := value.Method(i)
|
|
signature := method.Type()
|
|
if signature.NumIn() != 2 || signature.NumOut() != 2 || signature.In(0) != reflect.TypeOf((*gin.Context)(nil)) {
|
|
continue
|
|
}
|
|
if !signature.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
|
|
return failure.Wrap(codeControllerResult, "validate controller result failed", errors.New("second return value must implement error"))
|
|
}
|
|
formType := signature.In(1)
|
|
pointer := formType.Kind() == reflect.Ptr
|
|
if pointer {
|
|
formType = formType.Elem()
|
|
}
|
|
if formType.Kind() != reflect.Struct {
|
|
return failure.Wrap(codeControllerForm, "validate controller form failed", errors.New("form must be a struct or struct pointer"))
|
|
}
|
|
meta, exists := formType.FieldByName("Meta")
|
|
if !exists || meta.Type != reflect.TypeOf(Meta{}) {
|
|
return failure.Wrap(codeControllerMeta, "validate route metadata failed", errors.New("form must contain http.Meta"))
|
|
}
|
|
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", "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))
|
|
}
|
|
}
|
|
handler, err := s.controllerHandler(method, formType, pointer, meta)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, verb := range strings.Split(meta.Tag.Get("method"), ",") {
|
|
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, input: formType, output: signature.Out(0), security: meta.Tag.Get("security")})
|
|
}
|
|
}
|
|
}
|
|
return s.commit(planned)
|
|
}
|
|
|
|
// controllerHandler 创建绑定、可信字段注入、单次校验与响应处理链。
|
|
// 入参: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)
|
|
if err != nil || parsed <= 0 || parsed == 1<<63-1 {
|
|
return nil, failure.Wrap(codeBodyLimit, "validate route body limit failed", errors.New("invalid max-body-bytes"))
|
|
}
|
|
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
|
|
)
|
|
if errors.As(err, &large) {
|
|
status = http.StatusRequestEntityTooLarge
|
|
} else if errors.Is(err, request.ErrUnsupportedMediaType) {
|
|
status = http.StatusUnsupportedMediaType
|
|
}
|
|
s.writeResult(ctx, nil, err, status)
|
|
ctx.Abort()
|
|
return
|
|
}
|
|
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.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()
|
|
}
|
|
result := method.Call([]reflect.Value{reflect.ValueOf(ctx), input})
|
|
var (
|
|
err error
|
|
)
|
|
if !isNil(result[1]) {
|
|
err = result[1].Interface().(error)
|
|
}
|
|
if s.finishCanceled(ctx, err) {
|
|
return
|
|
}
|
|
s.writeResult(ctx, result[0].Interface(), err, 0)
|
|
}, nil
|
|
}
|
|
|
|
// isNil 检查允许判空的反射值,兼容具体错误类型。
|
|
// 入参:value 为 Controller 错误返回值。
|
|
// 返回:值为 nil 时为 true。
|
|
func isNil(value reflect.Value) bool {
|
|
switch value.Kind() {
|
|
case reflect.Ptr, reflect.Interface, reflect.Map, reflect.Slice, reflect.Chan, reflect.Func:
|
|
return value.IsNil()
|
|
}
|
|
return false
|
|
}
|
|
|
|
// inject 按字段名把可信公共参数覆盖到 Form,包括匿名嵌入指针。
|
|
// 入参:ctx 为认证后的请求,form 为可写结构体。
|
|
// 返回:读取或类型不匹配错误,绝不回退到客户端值。
|
|
func (s *Server) inject(ctx *gin.Context, form reflect.Value) error {
|
|
for _, name := range s.trustedFieldNames {
|
|
definition, exists := form.Type().FieldByName(name)
|
|
if !exists {
|
|
continue
|
|
}
|
|
field := form
|
|
for _, index := range definition.Index {
|
|
if field.Kind() == reflect.Ptr {
|
|
if field.IsNil() {
|
|
if !field.CanSet() {
|
|
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()))
|
|
}
|
|
field = field.Elem()
|
|
}
|
|
field = field.Field(index)
|
|
}
|
|
if !field.CanSet() {
|
|
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.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.WrapContext(ctx.Request.Context(), codeTrustedType, "assign trusted field failed", errors.New("trusted field type mismatch"))
|
|
}
|
|
field.Set(source)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// commit 用候选 Gin 引擎验证完整路由表,成功后一次替换,避免部分注册。
|
|
// 入参:planned 为本批新增路由。
|
|
// 返回:无效路由、冲突和冻结错误。
|
|
func (s *Server) commit(planned []route) error {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
if s.frozen || s.stopping {
|
|
return failure.Wrap(codeRouteFrozen, "register frozen HTTP routes failed", errors.New("HTTP routes are frozen"))
|
|
}
|
|
all := append(append([]route(nil), s.routes...), planned...)
|
|
candidate, err := s.buildEngine(all)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.engine, s.routes = candidate, all
|
|
return nil
|
|
}
|
|
|
|
// buildEngine 在独立引擎上执行 Gin 自身的路由冲突检查。
|
|
// 入参:routes 为候选完整路由计划。
|
|
// 返回:校验成功的引擎;Gin 的注册 panic 转为内部错误,不影响活动路由表。
|
|
func (s *Server) buildEngine(routes []route) (engine *gin.Engine, err error) {
|
|
defer func() {
|
|
if recover() != nil {
|
|
engine = nil
|
|
err = failure.Wrap(codeRoute, "validate Gin route registration failed", errors.New("invalid or conflicting Gin route"))
|
|
}
|
|
}()
|
|
engine = gin.New()
|
|
if err = engine.SetTrustedProxies(s.config.TrustedProxies); err != nil {
|
|
return nil, failure.Wrap(codeProxy, "configure route proxies failed", err)
|
|
}
|
|
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)
|
|
})
|
|
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"))
|
|
}
|
|
for _, handler := range item.handlers {
|
|
if handler == nil {
|
|
return nil, failure.Wrap(codeRouteHandler, "validate HTTP handler failed", errors.New("nil HTTP handler"))
|
|
}
|
|
}
|
|
engine.Handle(item.meta.Method, item.meta.Path, item.handlers...)
|
|
}
|
|
return engine, nil
|
|
}
|
|
|
|
// Routes 返回文档和注册验证可用的路由副本,不暴露 Handler 或业务依赖。
|
|
// 返回:最终完整路径和文档元数据。
|
|
func (s *Server) Routes() []Metadata {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
result := make([]Metadata, 0, len(s.routes))
|
|
for _, item := range s.routes {
|
|
result = append(result, item.meta)
|
|
}
|
|
return result
|
|
}
|
|
|
|
// Deadline 为原生流式 Handler 派生截止上下文,不缓冲或替换响应 Writer。
|
|
// 入参:duration 为连接最大时长,非正值保持原上下文。
|
|
// 返回:需要由流式业务监听 Request.Context 的 Gin 中间件。
|
|
func Deadline(duration time.Duration) gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
if duration <= 0 {
|
|
ctx.Next()
|
|
return
|
|
}
|
|
parent, cancel := context.WithTimeout(ctx.Request.Context(), duration)
|
|
defer cancel()
|
|
ctx.Request = ctx.Request.WithContext(parent)
|
|
ctx.Next()
|
|
}
|
|
}
|