From eb88ab15adaf23a61c783afe76b646855814d38a Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Wed, 15 May 2024 21:47:13 +0200 Subject: feat: add caching header (except on error pages) --- internal/server/error.go | 2 ++ internal/server/mux.go | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/internal/server/error.go b/internal/server/error.go index 51453f4..6994ad7 100644 --- a/internal/server/error.go +++ b/internal/server/error.go @@ -21,6 +21,8 @@ func createErrorHandler( Code: code, Message: message, } + w.Header().Set("Cache-Control", "no-store") + w.Header().Del("Vary") w.WriteHeader(code) if r.Header.Get("Fetch") == "true" { err = templates["error"].ExecuteTemplate(w, "main", indexData) diff --git a/internal/server/mux.go b/internal/server/mux.go index f49767b..af4a51b 100644 --- a/internal/server/mux.go +++ b/internal/server/mux.go @@ -101,6 +101,7 @@ func NewMux( Sources: cfg.Importer.Sources, Version: *versionInfo, } + w.Header().Add("Cache-Control", "max-age=86400") err := templates["index"].Execute(w, indexData) if err != nil { errorHandler(w, r, err.Error(), http.StatusInternalServerError) @@ -185,6 +186,8 @@ func NewMux( } } + w.Header().Add("Cache-Control", "max-age=300") + w.Header().Add("Vary", "Fetch") if r.Header.Get("Fetch") == "true" { w.Header().Add("Content-Type", "text/html; charset=utf-8") err = templates["options"].ExecuteTemplate(w, "results", tdata) @@ -203,6 +206,7 @@ func NewMux( return } + w.Header().Add("Cache-Control", "max-age=14400") err = templates["search"].Execute(w, TemplateData{ ExtraHeadHTML: cfg.Web.ExtraHeadHTML, Sources: cfg.Importer.Sources, @@ -234,6 +238,7 @@ func NewMux( return } + w.Header().Add("Cache-Control", "max-age=604800") w.Header().Set("Content-Type", "application/opensearchdescription+xml") err := templates["opensearch.xml"].ExecuteTemplate( w, @@ -254,7 +259,11 @@ func NewMux( }, ) - mux.Handle("/static/", http.FileServer(http.FS(frontend.Files))) + fs := http.FileServer(http.FS(frontend.Files)) + mux.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Cache-Control", "max-age=86400") + fs.ServeHTTP(w, r) + }) if liveReload { applyDevModeOverrides(cfg) -- cgit 1.4.1