Files
schreifuchs.ch/internal/server/static.go
T
2026-03-02 22:37:48 +01:00

51 lines
1.1 KiB
Go

package server
import (
"fmt"
"io/fs"
"log/slog"
"net/http"
"time"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
)
// registerStatic registers all the static files.
func registerStatic(mux *http.ServeMux) {
fileSystem := web.GetStaticFS()
// we still use go's fileServer to avoid unnecessary implementation
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 {
return err
}
if d.IsDir() {
return nil
}
path = "/" + path
slog.Info("registering file", "path", path)
mux.Handle(path, fileServer)
return nil
})
if err != nil {
slog.Error("could not register static files", "err", err)
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)
})
}
}