How to add default header to response returned in Gin golang? I wanted to add Cache-Control: public, max-age=604800, immutable
to the every response that I return.
Asked
Active
Viewed 5,034 times
2

Madiyor
- 761
- 9
- 23
-
Have you considered using [middleware](https://github.com/gin-gonic/gin#using-middleware)? – mkopriva Mar 27 '21 at 10:45
-
nope, how to use it – Madiyor Mar 27 '21 at 10:46
-
Here's an [example](https://github.com/alexander-melentyev/gin-nocache), look at the code to see how it's implemented, look at the readme to see how it's used. – mkopriva Mar 27 '21 at 10:49
-
ok, I look at that code – Madiyor Mar 27 '21 at 11:01
1 Answers
4
I have solved the above question with following code
r := gin.New()
r.Use(func() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Cache-Control", "public, max-age=604800, immutable")
}
}()
)
However, it is not really good idea to add the given header to every request. It is better to add the header to cdn or static items. It can be achieved with NGINX or Traefik.

Madiyor
- 761
- 9
- 23
-
I have used it with S3 storage and it is possible to add it there. It is not good place to add this header in gin golang – Madiyor Dec 03 '21 at 14:52