feat: 支持设置请求超时中间件

This commit is contained in:
2026-01-04 11:16:36 +08:00
parent 1830f0a571
commit 5e2964b5af
6 changed files with 70 additions and 14 deletions

View File

@@ -153,7 +153,7 @@ func (c controllerParser) setUriMeta(metaField reflect.StructField, cfg *UriConf
cfg.NoLogin = boolMetaParse(TagNameNoLogin) // 是否需要登录
// 最大执行时间
cfg.MaxExecTime = uint(0)
cfg.MaxExecTime = int64(0)
if tagVal := strings.ToLower(metaField.Tag.Get(TagNameMaxExecTime)); tagVal != "" {
if err := util.ConvertAssign(&cfg.MaxExecTime, tagVal); nil != err {
panic(cfg.Path + " : 最大执行时间配置错误(配置的值必须是无符号整型), 请检查配置 : " + err.Error())

View File

@@ -44,7 +44,7 @@ type UriConfig struct {
IsSse bool `json:"is_sse"` // 是否 SSE 连接
IsWebsocket bool `json:"is_ws"` // 是否 websocket 连接
OutputStrict bool `json:"output_strict"` // 接口是否为严格模式 : 不配置,可返回任意类型, 配置, 必须返回结构体或者map
MaxExecTime uint `json:"max_exec_time"` // 接口最大执行时间, 单位: ms, 配置为0则不验证, 注意, 超时后不会报错, 会打印一条warn日志, 如果配置了报警策略, 也会发送报警信息
MaxExecTime int64 `json:"max_exec_time"` // 接口最大执行时间, 单位: ms, 配置为0则不验证, 注意, 超时后不会报错, 会打印一条warn日志, 如果配置了报警策略, 也会发送报警信息
HookSync bool `json:"hook_sync"` // 接口主逻辑执行完成之后hook是否同步执行, 默认异步执行
NoLogin bool `json:"no_login"` // 接口是否需要登录(无需登录, 则有token就验证, 无token不验证)
ParamIsPtr bool `json:"param_is_ptr"` // 参数是否指针类型

View File

@@ -203,6 +203,8 @@ func (s *server) Group(routerPrefix string, middlewareList []gin.HandlerFunc, co
} else {
apiMiddlewareList = append(apiMiddlewareList, runtime.FuncForPC(reflect.ValueOf(s.RequestHandler).Pointer()).Name())
}
// 设置 超时 函数描述
apiMiddlewareList = append(apiMiddlewareList, runtime.FuncForPC(reflect.ValueOf(middleware.Timeout).Pointer()).Name())
// 设置 logic 函数描述
apiMiddlewareList = append(apiMiddlewareList, runtime.FuncForPC(itemUriCfg.ApiLogicFunc.Func.Pointer()).Name())
@@ -231,21 +233,25 @@ func (s *server) Group(routerPrefix string, middlewareList []gin.HandlerFunc, co
// registerRouter 注册路由
func (s *server) registerRouter(routerGroup *gin.RouterGroup, method string, itemUriCfg UriConfig, handleFunc gin.HandlerFunc) {
funcList := []gin.HandlerFunc{
middleware.Timeout(itemUriCfg.MaxExecTime), // 超时处理
handleFunc,
}
switch method {
case http.MethodGet:
routerGroup.GET(itemUriCfg.Path, handleFunc)
case http.MethodHead:
routerGroup.HEAD(itemUriCfg.Path, handleFunc)
routerGroup.HEAD(itemUriCfg.Path, funcList...)
case http.MethodPost:
routerGroup.POST(itemUriCfg.Path, handleFunc)
routerGroup.POST(itemUriCfg.Path, funcList...)
case http.MethodPut:
routerGroup.PUT(itemUriCfg.Path, handleFunc)
routerGroup.PUT(itemUriCfg.Path, funcList...)
case http.MethodPatch:
routerGroup.PATCH(itemUriCfg.Path, handleFunc)
routerGroup.PATCH(itemUriCfg.Path, funcList...)
case http.MethodDelete:
routerGroup.DELETE(itemUriCfg.Path, handleFunc)
routerGroup.DELETE(itemUriCfg.Path, funcList...)
case http.MethodOptions:
routerGroup.OPTIONS(itemUriCfg.Path, handleFunc)
routerGroup.OPTIONS(itemUriCfg.Path, funcList...)
case http.MethodTrace:
panic(`method Trace is not supported`)
default: