package middleware import ( "context" "github.com/gin-gonic/gin" "net/http" "time" ) // timeout middleware wraps the request context with a timeout func TimeoutMiddleware(timeout time.Duration) func(c *gin.Context) { return func(c *gin.Context) { //是否超时,都会执行,进行收尾 // 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.JSON(http.StatusOK, gin.H{ "code": 400, "msg": "数据有误", "data": nil, }) c.Abort() } c.JSON(http.StatusOK, "hello") //是否超时,都会执行,进行收尾 //cancel to clear resources after finished cancel() }() //是否超时,都会执行 // replace request with context wrapped request c.Request = c.Request.WithContext(ctx) c.Next()//实际调用具体的handler处理业务,实际还在这个方法中,所以业务执行结束会回到中间件中执行中间件中的defer函数 } }