fix(backend): fix static files headers

This commit is contained in:
Łukasz Mierzwa
2020-10-18 12:31:14 +01:00
committed by Łukasz Mierzwa
parent 640c701295
commit c1dc75e30c
2 changed files with 5 additions and 32 deletions

View File

@@ -109,36 +109,14 @@ func serverStaticFiles(prefix string, fs *binaryFileSystem) func(next http.Handl
if ct == "" {
ct = "application/octet-stream"
}
w.Header().Set("Content-Type", ct)
w.Header().Set("Cache-Control", "public, max-age=31536000")
expiresTime := time.Now().AddDate(0, 0, 365).Format(http.TimeFormat)
w.Header().Set("Expires", expiresTime)
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, fl)
})
}
}
func setStaticHeaders(prefix string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, prefix) {
w.Header().Set("Cache-Control", "public, max-age=31536000")
expiresTime := time.Now().AddDate(0, 0, 365).Format(http.TimeFormat)
w.Header().Set("Expires", expiresTime)
}
next.ServeHTTP(w, r)
})
}
}
func clearStaticHeaders(prefix string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, prefix) {
w.Header().Del("Cache-Control")
w.Header().Del("Expires")
}
next.ServeHTTP(w, r)
})
}
}

View File

@@ -91,7 +91,6 @@ func setupRouter(router *chi.Mux) {
compressor := middleware.NewCompressor(flate.DefaultCompression)
router.Use(compressor.Handler)
router.Use(setStaticHeaders(getViewURL("/static/")))
router.Use(serverStaticFiles(getViewURL("/"), staticBuildFileSystem))
// next 2 lines are to allow service raw sources so sentry can fetch source maps
router.Use(serverStaticFiles(getViewURL("/static/js/"), staticSrcFileSystem))
@@ -99,14 +98,10 @@ func setupRouter(router *chi.Mux) {
// compressed sources are under /static/js/main.js and reference ../static/js/main.js
// so we end up with /static/static/js
router.Use(serverStaticFiles(getViewURL("/static/static/js/"), staticSrcFileSystem))
router.Use(clearStaticHeaders(getViewURL("/static/")))
router.Use(cors.Handler(cors.Options{
AllowOriginFunc: func(r *http.Request, origin string) bool {
return true
},
// AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
AllowedMethods: []string{"GET", "POST", "DELETE"},
AllowedHeaders: []string{"Origin"},
ExposedHeaders: []string{"Content-Length"},