feat: 支持设置请求超时中间件
This commit is contained in:
34
middleware/timeout.go
Normal file
34
middleware/timeout.go
Normal file
@@ -0,0 +1,34 @@
|
||||
// Package middleware ...
|
||||
//
|
||||
// Description : middleware ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2026-01-04 10:17
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/timeout"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Timeout 超时处理中间件
|
||||
func Timeout(ttl int64) func(ctx *gin.Context) {
|
||||
if ttl <= 0 {
|
||||
// 未设置超时
|
||||
return func(ctx *gin.Context) {
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
// 设置超时中间件, 单位: ms
|
||||
return timeout.New(
|
||||
timeout.WithTimeout(time.Duration(ttl)*time.Millisecond),
|
||||
timeout.WithResponse(func(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusRequestTimeout, gin.H{"code": http.StatusRequestTimeout, "msg": "请求超时"})
|
||||
ctx.Abort()
|
||||
}),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user