Skip serving cached page if the user is logged in or the request is not a GET.

This commit is contained in:
mikestefanello 2021-12-19 13:01:52 -05:00
parent 3ad6a5f87f
commit 098d1b7eb2
2 changed files with 15 additions and 2 deletions

View File

@ -2,8 +2,11 @@ package middleware
import (
"fmt"
"net/http"
"time"
"goweb/context"
"github.com/eko/gocache/v2/cache"
"github.com/eko/gocache/v2/marshaler"
"github.com/go-redis/redis/v8"
@ -17,9 +20,19 @@ type CachedPage struct {
Headers map[string]string
}
func PageCache(ch *cache.Cache) echo.MiddlewareFunc {
func ServeCachedPage(ch *cache.Cache) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Skip non GET requests
if c.Request().Method != http.MethodGet {
return next(c)
}
// Skip if the user is authenticated
if c.Get(context.AuthenticatedUserKey) != nil {
return next(c)
}
res, err := marshaler.New(ch).Get(c.Request().Context(), c.Request().URL.String(), new(CachedPage))
if err != nil {
if err == redis.Nil {

View File

@ -51,7 +51,7 @@ func BuildRouter(c *services.Container) {
echomw.TimeoutWithConfig(echomw.TimeoutConfig{
Timeout: c.Config.App.Timeout,
}),
middleware.PageCache(c.Cache),
middleware.ServeCachedPage(c.Cache),
session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))),
echomw.CSRFWithConfig(echomw.CSRFConfig{
TokenLookup: "form:csrf",