all repos — searchix @ eb88ab15adaf23a61c783afe76b646855814d38a

Search engine for NixOS, nix-darwin, home-manager and NUR users

feat: add caching header (except on error pages)
Alan Pearce alan@alanpearce.eu
Wed, 15 May 2024 21:47:13 +0200
commit

eb88ab15adaf23a61c783afe76b646855814d38a

parent

fa97ca832d6dc301dabb5d9c76730630f99534e0

2 files changed, 12 insertions(+), 1 deletions(-)

jump to
M internal/server/error.gointernal/server/error.go
@@ -21,6 +21,8 @@ Version:       *versionInfo, 			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)
M internal/server/mux.gointernal/server/mux.go
@@ -101,6 +101,7 @@ ExtraHeadHTML: cfg.Web.ExtraHeadHTML, 			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 @@ tdata.Prev = "search?" + q.Encode() 				}
 			}
 
+			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 @@ 				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 @@ 				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 @@ } 		},
 	)
 
-	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)