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")
}
consider this case: