add static assets caching

This commit is contained in:
Ruidy 2024-08-19 15:00:38 +02:00
parent 1d1c871b8a
commit 8a6531f50e
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
2 changed files with 45 additions and 0 deletions

View file

@ -0,0 +1,44 @@
package server
import (
"fmt"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/rjNemo/underscore"
)
const (
defaultTTL = 2592000 // 1 month
)
// CachingMiddleware adds caching headers.
// ttl is the max age of the cache in seconds. If ttl is 0, the default value wil be used.
func CachingMiddleware(ttl int, fileTypes ...string) echo.MiddlewareFunc {
if ttl == 0 {
ttl = defaultTTL
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
shouldCache := underscore.Any(fileTypes, func(v string) bool {
return strings.HasSuffix(c.Request().RequestURI, fmt.Sprintf(".%s", v))
})
if shouldCache {
s := strings.Split(c.Request().RequestURI, "/")
etag := s[len(s)-1]
c.Response().Header().Set("Etag", etag)
c.Response().Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", ttl))
if match := c.Request().Header.Get("If-None-Match"); match != "" {
if strings.Contains(match, etag) {
return c.NoContent(http.StatusNotModified)
}
}
}
return next(c)
}
}
}

View file

@ -102,6 +102,7 @@ func NewRouter(fs embed.FS, debug bool, secret string, origins []string) *echo.E
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{AllowOrigins: origins}))
e.Use(sentryecho.New(sentryecho.Options{}))
e.Use(SentryTracingMiddleware)
e.Use(CachingMiddleware(0, "js", "css", "png", "ico"))
e.Use(session.Middleware(sessions.NewCookieStore([]byte(secret))))
// static assets
e.StaticFS("/static", echo.MustSubFS(fs, "assets"))