gin-contrib / timeout

Timeout middleware for Gin
MIT License
185 stars 38 forks source link

Bug: the result will be incorrect when call gin.Context.Writer.Status() in our custom gin middleware used after this(#46) #47

Closed zhyee closed 1 year ago

zhyee commented 1 year ago

consider this case:

func Timeout() gin.HandlerFunc {
    return timeout.New(timeout.WithTimeout(time.Second*1),
        timeout.WithHandler(func(ctx *gin.Context) {
            ctx.Next()
        }),
        timeout.WithResponse(func(ctx *gin.Context) {
            ctx.String(http.StatusRequestTimeout, "timeout")
        }),
    )
}

func Logger() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Next()
        // access the status we are sending
        status := c.Writer.Status() // Bug: in any middleware used after this middleware, the result will always be 200.
        log.Println(status)
    }
}

func main() {
    r := gin.New()
    r.Use(Timeout())
    r.Use(Logger())

    r.GET("/test", func(c *gin.Context) {
        c.Status(http.StatusInternalServerError)
    })
    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}
fr-wentianqi commented 1 year ago

same issue here, by moving your timeout middleware down underneath the logger middleware will solve the issue

appleboy commented 1 year ago

fix in #46