feat: caching headers
This commit is contained in:
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/handlehome"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/templer"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
|
||||
"github.com/studio-b12/gowebdav"
|
||||
)
|
||||
|
||||
func (s *Server) RegisterRoutes() (h http.Handler) {
|
||||
@@ -24,17 +26,26 @@ func (s *Server) RegisterRoutes() (h http.Handler) {
|
||||
return h
|
||||
}
|
||||
|
||||
func registerOther() http.Handler {
|
||||
func registerOther() (h http.Handler) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
pager := page.New()
|
||||
webdavClient := gowebdav.NewClient("https://cloud.schreifuchs.ch/remote.php/dav/files/test/website", "test", os.Getenv("TEST_PW"))
|
||||
if err := webdavClient.Connect(); err != nil {
|
||||
slog.Error("could not connect webdavClient", "err", err, "pw", os.Getenv("TEST_PW"))
|
||||
}
|
||||
|
||||
pager := page.New(webdavClient)
|
||||
|
||||
_ = handlehome.New(mux, pager)
|
||||
|
||||
mux.Handle("/", http.FileServer(http.FS(web.GetStaticFS())))
|
||||
|
||||
translator := translate.New()
|
||||
return translator.Middleware(mux)
|
||||
|
||||
h = mux
|
||||
h = translator.Middleware(h)
|
||||
h = cacheMiddleware(time.Second * 45)(h)
|
||||
return h
|
||||
}
|
||||
|
||||
func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user