gin icon indicating copy to clipboard operation
gin copied to clipboard

[feature] option for Server-Timing header in static middleware

Open benmccann opened this issue 4 years ago • 1 comments

I'd like the static middleware to add a Server-Timing header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing

This would allow me to better understand whether an asset is being served slowly because of some issue on the machine or because of network

I tried to implement myself with a middleware but found out it's not really possible because it would require me to write the Server-Timing header after Next is called which isn't well supported

benmccann avatar Jun 05 '21 13:06 benmccann

Hi, kind of necroing, but you can do this by hijacking the context's writer:

type afterMiddlewareWriter struct {
	gin.ResponseWriter
}

func (w *afterMiddlewareWriter) WriteHeader(statusCode int) {
	// You can freely add headers here using the structs fields
	w.Header().Add("My-Header", "My Value")
	w.ResponseWriter.WriteHeader(statusCode)
}

func AfterMiddleware(c *gin.Context) {
	c.Writer = &afterMiddlewareWriter{c.Writer}
	c.Next()
}

func main() {
	r := gin.Default()
	r.Use(AfterMiddleware)
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"key": "value",
		})
	})
}

joaohaas avatar Mar 27 '23 19:03 joaohaas