From 921bf66d204585a442c76e230f0c66417d8b8041 Mon Sep 17 00:00:00 2001 From: soup Date: Fri, 15 Nov 2024 14:03:04 -0500 Subject: [PATCH] Static asset caching --- backend/routes/routes.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/backend/routes/routes.go b/backend/routes/routes.go index f2e0261..ea7e4bf 100644 --- a/backend/routes/routes.go +++ b/backend/routes/routes.go @@ -5,6 +5,7 @@ import ( "net/http" "shelves/backend/httpx" "strings" + "time" "shelves" ) @@ -28,9 +29,28 @@ func redirectSetup(next http.Handler) http.Handler { }) } +func ServeStatic() http.Handler { + inner := http.StripPrefix("/static/", http.FileServerFS(shelves.Frontend)) + startup := time.Now().UTC() + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ims := r.Header.Get("If-Modified-Since") + imsTime, _ := time.Parse(http.TimeFormat, ims) + imsTime = imsTime.Add(time.Second * 10) + + if imsTime.Before(startup) { + w.Header().Add("Last-Modified", startup.Format(http.TimeFormat)) + w.Header().Add("Cache-Control", "public, max-age=0, stale-while-revalidate=9999999") + inner.ServeHTTP(w, r) + } else { + w.WriteHeader(http.StatusNotModified) + } + }) +} + func Routes() http.Handler { mux := http.NewServeMux() - mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(shelves.Frontend))) + mux.Handle("GET /static/", ServeStatic()) mux.HandleFunc("GET /{$}", HomeGet) mux.HandleFunc("GET /setup", SetupGet) mux.HandleFunc("POST /setup", SetupPost)