Merge pull request #336 from Antolius/static-assets-cache-control

Add Cache-Control header
This commit is contained in:
Matt Baer 2020-09-04 16:12:29 -04:00 committed by GitHub
commit c31a87fb76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 52 additions and 0 deletions

View File

@ -926,3 +926,10 @@ func sendRedirect(w http.ResponseWriter, code int, location string) int {
w.WriteHeader(code)
return code
}
func cacheControl(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "public, max-age=604800, immutable")
next.ServeHTTP(w, r)
})
}

View File

@ -26,6 +26,7 @@ import (
func (app *App) InitStaticRoutes(r *mux.Router) {
// Handle static files
fs := http.FileServer(http.Dir(filepath.Join(app.cfg.Server.StaticParentDir, staticDir)))
fs = cacheControl(fs)
app.shttp = http.NewServeMux()
app.shttp.Handle("/", fs)
r.PathPrefix("/").Handler(fs)

38
routes_test.go Normal file
View File

@ -0,0 +1,38 @@
package writefreely
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/mux"
)
func TestCacheControlForStaticFiles(t *testing.T) {
app := NewApp("testdata/config.ini")
if err := app.LoadConfig(); err != nil {
t.Fatalf("Could not create an app; %v", err)
}
router := mux.NewRouter()
app.InitStaticRoutes(router)
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/style.css", nil)
router.ServeHTTP(rec, req)
if code := rec.Result().StatusCode; code != http.StatusOK {
t.Fatalf("Could not get /style.css, got HTTP status %d", code)
}
actual := rec.Result().Header.Get("Cache-Control")
expectedDirectives := []string{
"public",
"max-age",
"immutable",
}
for _, expected := range expectedDirectives {
if !strings.Contains(actual, expected) {
t.Errorf("Expected Cache-Control header to contain '%s', but was '%s'", expected, actual)
}
}
}

1
testdata/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
!config.ini

2
testdata/config.ini vendored Normal file
View File

@ -0,0 +1,2 @@
[server]
static_parent_dir = testdata

3
testdata/static/style.css vendored Normal file
View File

@ -0,0 +1,3 @@
body {
background-color: lightblue;
}