mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-12 13:46:51 +00:00
add static assets caching
This commit is contained in:
parent
1d1c871b8a
commit
8a6531f50e
2 changed files with 45 additions and 0 deletions
44
internal/server/middleware.go
Normal file
44
internal/server/middleware.go
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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(middleware.CORSWithConfig(middleware.CORSConfig{AllowOrigins: origins}))
|
||||||
e.Use(sentryecho.New(sentryecho.Options{}))
|
e.Use(sentryecho.New(sentryecho.Options{}))
|
||||||
e.Use(SentryTracingMiddleware)
|
e.Use(SentryTracingMiddleware)
|
||||||
|
e.Use(CachingMiddleware(0, "js", "css", "png", "ico"))
|
||||||
e.Use(session.Middleware(sessions.NewCookieStore([]byte(secret))))
|
e.Use(session.Middleware(sessions.NewCookieStore([]byte(secret))))
|
||||||
// static assets
|
// static assets
|
||||||
e.StaticFS("/static", echo.MustSubFS(fs, "assets"))
|
e.StaticFS("/static", echo.MustSubFS(fs, "assets"))
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue