From 2006464b9fd8be1bbcc22ee0468173de1dfec8f4 Mon Sep 17 00:00:00 2001
From: ale <ale@incal.net>
Date: Sun, 10 Nov 2024 12:44:22 +0000
Subject: [PATCH] Only set Cache-Control header on status 200

---
 ui/ui.go | 23 +++++++++++++++++++----
 1 file changed, 19 insertions(+), 4 deletions(-)

diff --git a/ui/ui.go b/ui/ui.go
index c7d4ad19..51feb71c 100644
--- a/ui/ui.go
+++ b/ui/ui.go
@@ -72,10 +72,7 @@ func Build(config *Config, urls common.URLMap) (http.Handler, *common.Renderer,
 	})))
 
 	// Add cache-friendly headers.
-	h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
-		w.Header().Set("Cache-Control", "max-age=86400")
-		mux.ServeHTTP(w, req)
-	})
+	h := withCacheHeaders(mux)
 
 	return h, renderer, nil
 }
@@ -134,3 +131,21 @@ func toJSON(obj interface{}) string {
 	data, _ := json.Marshal(obj)
 	return string(data)
 }
+
+type cachedResponseWriter struct {
+	http.ResponseWriter
+}
+
+func (c *cachedResponseWriter) WriteHeader(statusCode int) {
+	if statusCode == http.StatusOK {
+		c.ResponseWriter.Header().Set("Cache-Control", "max-age=86400")
+	}
+	c.ResponseWriter.WriteHeader(statusCode)
+}
+
+func withCacheHeaders(h http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+		cw := &cachedResponseWriter{ResponseWriter: w}
+		h.ServeHTTP(cw, req)
+	})
+}
-- 
GitLab