go: add a simple caching middleware for assets
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
leo 2023-05-31 22:29:52 +02:00
parent dbd0e9d01d
commit ffc9b74c75
Signed by: wanderer
SSH Key Fingerprint: SHA256:Dp8+iwKHSlrMEHzE3bJnPng70I7LEsa3IJXRH/U+idQ
2 changed files with 23 additions and 1 deletions

@ -37,7 +37,7 @@ func (a *App) SetupRoutes() {
)
// alternative:
// e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", assets)))
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/assets/", assets)))
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/assets/", assets)), handlers.MiddlewareCache)
e.GET("/healthz", handlers.Healthz())
e.GET("/health", handlers.Healthz())

@ -6,6 +6,7 @@ package handlers
import (
"context"
"net/http"
"strings"
moduser "git.dotya.ml/mirre-mt/pcmt/modules/user"
"github.com/labstack/echo-contrib/session"
@ -97,3 +98,24 @@ func MiddlewareSession(next echo.HandlerFunc) echo.HandlerFunc {
return next(c)
}
}
var cacheExtensions = [2]string{".png", ".svg"}
func MiddlewareCache(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cache := false
for _, v := range cacheExtensions {
if strings.HasSuffix(c.Request().URL.Path, v) {
cache = true
break
}
}
if cache {
c.Response().Header().Set(echo.HeaderCacheControl, "300")
}
return next(c)
}
}