diff --git a/cache.go b/cache.go index b1b1be9..587b0c4 100644 --- a/cache.go +++ b/cache.go @@ -11,6 +11,7 @@ package writefreely import ( + "net/http" "sync" "time" ) @@ -67,3 +68,10 @@ func GetPostsCache(userID int64) *[]PublicPost { } return pci.Posts } + +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) + }) +} diff --git a/routes.go b/routes.go index 47c4f19..efe1f21 100644 --- a/routes.go +++ b/routes.go @@ -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) diff --git a/routes_test.go b/routes_test.go new file mode 100644 index 0000000..9669e6e --- /dev/null +++ b/routes_test.go @@ -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) + } + } +} diff --git a/testdata/.gitignore b/testdata/.gitignore new file mode 100644 index 0000000..0573cf2 --- /dev/null +++ b/testdata/.gitignore @@ -0,0 +1 @@ +!config.ini diff --git a/testdata/config.ini b/testdata/config.ini new file mode 100644 index 0000000..ed3a86d --- /dev/null +++ b/testdata/config.ini @@ -0,0 +1,2 @@ +[server] +static_parent_dir = testdata diff --git a/testdata/static/style.css b/testdata/static/style.css new file mode 100644 index 0000000..eed8207 --- /dev/null +++ b/testdata/static/style.css @@ -0,0 +1,3 @@ +body { + background-color: lightblue; +}