Added cache control middleware.

This commit is contained in:
mikestefanello 2021-12-03 08:18:40 -05:00
parent 70d777d09e
commit 3c2c698269
2 changed files with 31 additions and 14 deletions

20
middleware/cache.go Normal file
View file

@ -0,0 +1,20 @@
package middleware
import (
"fmt"
"github.com/labstack/echo/v4"
)
func CacheControl(maxAge int) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
v := "no-cache, no-store"
if maxAge > 0 {
v = fmt.Sprintf("public, max-age=%d", maxAge)
}
c.Response().Header().Set("Cache-Control", v)
return next(c)
}
}
}

View file

@ -3,10 +3,12 @@ package router
import ( import (
"net/http" "net/http"
"goweb/middleware"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session" "github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware" echomw "github.com/labstack/echo/v4/middleware"
"goweb/container" "goweb/container"
"goweb/controllers" "goweb/controllers"
@ -16,28 +18,23 @@ const StaticDir = "static"
func BuildRouter(c *container.Container) { func BuildRouter(c *container.Container) {
// Middleware // Middleware
c.Web.Use(middleware.RemoveTrailingSlashWithConfig(middleware.TrailingSlashConfig{ c.Web.Use(echomw.RemoveTrailingSlashWithConfig(echomw.TrailingSlashConfig{
RedirectCode: http.StatusMovedPermanently, RedirectCode: http.StatusMovedPermanently,
})) }))
c.Web.Use(middleware.RequestID()) c.Web.Use(echomw.RequestID())
c.Web.Use(middleware.Recover()) c.Web.Use(echomw.Recover())
c.Web.Use(middleware.Gzip()) c.Web.Use(echomw.Gzip())
c.Web.Use(middleware.Logger()) c.Web.Use(echomw.Logger())
// TODO: needs cache control headers
c.Web.Use(session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey)))) c.Web.Use(session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))))
c.Web.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{ c.Web.Use(echomw.CSRFWithConfig(echomw.CSRFConfig{
TokenLookup: "form:csrf", TokenLookup: "form:csrf",
})) }))
// Static files with proper cache control // Static files with proper cache control
// funcmap.File() should be used in templates to append a cache key to the URL in order to break cache // funcmap.File() should be used in templates to append a cache key to the URL in order to break cache
// after each server restart // after each server restart
c.Web.Group("", func(next echo.HandlerFunc) echo.HandlerFunc { c.Web.Group("", middleware.CacheControl(15552000)).
return func(c echo.Context) error { Static("/", StaticDir)
c.Response().Header().Set("Cache-Control", "public, max-age=15552000")
return next(c)
}
}).Static("/", StaticDir)
// Base controller // Base controller
ctr := controllers.NewController(c) ctr := controllers.NewController(c)