Merge pull request #603 from prymitive/fix-expires

fix(backend): correctly handle expires for static files
This commit is contained in:
Łukasz Mierzwa
2019-04-09 20:21:18 +01:00
committed by GitHub
2 changed files with 18 additions and 7 deletions

View File

@@ -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)
}
}
}
}

View File

@@ -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