From ba34e927919bfa60af05b9a199d86fb3d14d807b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Mierzwa?= Date: Tue, 9 Apr 2019 19:48:48 +0100 Subject: [PATCH] fix(backend): correctly handle expires for static files We can't set any headers after c.Abort() was called (which will happen in the static files middleware if file was found) so we need to refactor this code. New logic will be: set all headers early, if file is found response will include those, later add second middleware that clears those headers, it will only be hit if file wasn't found, so we'll clear headers on all 404s --- assets.go | 20 ++++++++++++++------ main.go | 5 ++++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/assets.go b/assets.go index 9cd854144..abec33384 100644 --- a/assets.go +++ b/assets.go @@ -90,15 +90,23 @@ func serveFileOr404(path string, contentType string, c *gin.Context) { c.File(path) } -func staticHeaders(prefix string) gin.HandlerFunc { +func setStaticHeaders(prefix string) gin.HandlerFunc { return func(c *gin.Context) { if strings.HasPrefix(c.Request.URL.Path, prefix) { + c.Header("Cache-Control", "public, max-age=31536000") + expiresTime := time.Now().AddDate(0, 0, 365).Format(http.TimeFormat) + c.Header("Expires", expiresTime) + c.Next() + } + } +} + +func clearStaticHeaders(prefix string) gin.HandlerFunc { + return func(c *gin.Context) { + if strings.HasPrefix(c.Request.URL.Path, prefix) { + c.Header("Cache-Control", "") + c.Header("Expires", "") c.Next() - if c.IsAborted() { - c.Header("Cache-Control", "public, max-age=31536000") - expiresTime := time.Now().AddDate(0, 0, 365).Format(http.TimeFormat) - c.Header("Expires", expiresTime) - } } } } diff --git a/main.go b/main.go index a420d072b..814d3507c 100644 --- a/main.go +++ b/main.go @@ -55,7 +55,8 @@ func getViewURL(sub string) string { func setupRouter(router *gin.Engine) { router.Use(gzip.Gzip(gzip.DefaultCompression)) - router.Use(staticHeaders(getViewURL("/static/"))) + + router.Use(setStaticHeaders(getViewURL("/static/"))) router.Use(static.Serve(getViewURL("/"), staticBuildFileSystem)) // next 2 lines are to allow service raw sources so sentry can fetch source maps router.Use(static.Serve(getViewURL("/static/js/"), staticSrcFileSystem)) @@ -63,6 +64,8 @@ func setupRouter(router *gin.Engine) { // compressed sources are under /static/js/main.js and reference ../static/js/main.js // so we end up with /static/static/js router.Use(static.Serve(getViewURL("/static/static/js/"), staticSrcFileSystem)) + router.Use(clearStaticHeaders(getViewURL("/static/"))) + router.Use(cors.New(cors.Config{ // This works different than AllowAllOrigins=true // 1. AllowAllOrigins will cause responses to include