-
-
Notifications
You must be signed in to change notification settings - Fork 159
Open
Description
func timeoutMiddleware(timeout time.Duration) func(c *gin.Context) {
return func(c *gin.Context) {
// 若无自定义超时设置,默认设置超时
_, ok := c.Request.Context().Deadline()
if ok {
c.Next()
return
}
// wrap the request context with a timeout
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
defer func() {
// check if context timeout was reached
if ctx.Err() == context.DeadlineExceeded {
// write response and abort the request
c.Writer.WriteHeader(http.StatusGatewayTimeout)
c.Abort()
}
// cancel to clear resources after finished
cancel()
}()
// replace request with context wrapped request
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}这个中间件是先c.Next()再进入defer func(),c.Writer.WriteHeader(http.StatusGatewayTimeout)还有意义吗,为什么不监听超时呢
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels