How to implement timeout on gin framework?

I need to implement a request timeout on top of gin, than i created this middleware:

func Filter(t time.Duration) func(c *gin.Context) {
	return func(c *gin.Context) {
		finish := make(chan struct{})

		go func() {
			c.Next()
			finish <- struct{}{}
		}()

		select {
		case <-time.After(t):
			c.JSON(504, "timeout")
			c.Abort()
		case <-finish:
		}
	}
}

It actually works, the user get the timeout on screen, but later on log, i get errors:

[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 504 with 200
[GIN-debug] [ERROR] Conn.Write wrote more than the declared Content-Length
[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with 500

There is any way to 100% cancel the request? seams that it is stil running after the timeout

Try returning after calling c.Abort, and make sure you don’t try to set headers in a handler up the chain.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.