feat: caching headers

This commit is contained in:
2026-03-02 22:37:48 +01:00
parent 19fb5b9292
commit e689ab08c9
19 changed files with 292 additions and 55 deletions
+13 -1
View File
@@ -1,9 +1,11 @@
package server
import (
"fmt"
"io/fs"
"log/slog"
"net/http"
"time"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
)
@@ -13,7 +15,7 @@ func registerStatic(mux *http.ServeMux) {
fileSystem := web.GetStaticFS()
// we still use go's fileServer to avoid unnecessary implementation
fileServer := http.FileServer(http.FS(fileSystem))
fileServer := cacheMiddleware(time.Hour * 24)(http.FileServer(http.FS(fileSystem)))
err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
@@ -36,3 +38,13 @@ func registerStatic(mux *http.ServeMux) {
panic(err)
}
}
// cacheMiddleware adds Cache-Control headers to the response.
func cacheMiddleware(maxAge time.Duration) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds()))
next.ServeHTTP(w, r)
})
}
}