代码拉取完成,页面将自动刷新
package httpServer
// http接口超时控制
import (
"fmt"
"time"
"gitee.com/wu-jin-feng/kinfu/fgin"
"github.com/gin-contrib/timeout"
"github.com/gin-gonic/gin"
)
var Logger *fgin.FginSugaredLogger
func init() {
fgin.RegisteHttpPlug("http_timeout", &HttpTimeout{})
}
type HttpTimeout struct {
AllTimeout int `yaml:"all_timeout" json:"all_timeout" mapstructure:"all_timeout"` // 总控制的超时时间
RouteItems []HttpTimeoutItem `yaml:"route_items" json:"route_items" mapstructure:"route_items"` // 特别路由需要独立时间控制 单位s
}
type HttpTimeoutItem struct {
Route string `yaml:"route" json:"route" mapstructure:"route"` // 需要路由全称
Timeout int `yaml:"timeout" json:"timeout" mapstructure:"timeout"` // 单位s
}
func (s *HttpTimeout) Start(e *gin.Engine, logger *fgin.FginSugaredLogger) {
e.Use(s.TimeMiddware)
Logger = logger
Logger.Info("http_timeout注册成功")
}
func (s *HttpTimeout) TimeMiddware(ctx *gin.Context) {
nowTimeout := s.AllTimeout
for _, item := range s.RouteItems {
if ctx.Request.URL.Path == item.Route {
nowTimeout = item.Timeout
break
}
}
timeoutMiddware := timeout.New(
timeout.WithTimeout(time.Duration(nowTimeout)*time.Second),
timeout.WithHandler(func(c *gin.Context) {
// newContext, cancel := context.WithTimeout(c.Request.Context(), time.Duration(nowTimeout)*time.Second)
c.Next()
}),
timeout.WithResponse(func(c *gin.Context) {
Logger.Warn(fmt.Sprintf("%s, 耗时超过 %d s", c.Request.URL.Path, s.AllTimeout))
fgin.ReturnJson(c, 504, "", fmt.Errorf("请求超时"))
c.Abort()
}))
timeoutMiddware(ctx)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。