1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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函数
}
}