Skip serving cached page if the user is logged in or the request is not a GET.
This commit is contained in:
parent
3ad6a5f87f
commit
098d1b7eb2
@ -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 {
|
||||
|
@ -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",
|
||||
|
Loading…
Reference in New Issue
Block a user