saasitone/pkg/middleware/cache.go

75 lines
1.9 KiB
Go
Raw Normal View History

2021-12-03 05:18:40 -08:00
package middleware
import (
"errors"
2021-12-03 05:18:40 -08:00
"fmt"
"net/http"
2021-12-06 11:53:28 -08:00
"time"
2021-12-03 05:18:40 -08:00
"github.com/labstack/echo/v4"
2024-07-09 17:57:05 -07:00
"git.grosinger.net/tgrosinger/saasitone/pkg/context"
"git.grosinger.net/tgrosinger/saasitone/pkg/log"
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
2021-12-03 05:18:40 -08:00
)
2021-12-21 17:49:05 -08:00
// ServeCachedPage attempts to load a page from the cache by matching on the complete request URL
// If a page is cached for the requested URL, it will be served here and the request terminated.
// Any request made by an authenticated user or that is not a GET will be skipped.
func ServeCachedPage(t *services.TemplateRenderer) echo.MiddlewareFunc {
2021-12-07 18:36:57 -08:00
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
// Skip non GET requests
if ctx.Request().Method != http.MethodGet {
return next(ctx)
}
// Skip if the user is authenticated
if ctx.Get(context.AuthenticatedUserKey) != nil {
return next(ctx)
}
2021-12-21 17:49:05 -08:00
// Attempt to load from cache
page, err := t.GetCachedPage(ctx, ctx.Request().URL.String())
2021-12-07 18:36:57 -08:00
if err != nil {
switch {
case errors.Is(err, services.ErrCacheMiss):
case context.IsCanceledError(err):
return nil
default:
log.Ctx(ctx).Error("failed getting cached page",
"error", err,
)
2021-12-07 18:36:57 -08:00
}
return next(ctx)
}
2021-12-07 18:36:57 -08:00
2021-12-21 17:49:05 -08:00
// Set any headers
2021-12-07 18:36:57 -08:00
if page.Headers != nil {
for k, v := range page.Headers {
ctx.Response().Header().Set(k, v)
2021-12-07 18:36:57 -08:00
}
}
2021-12-21 17:49:05 -08:00
log.Ctx(ctx).Debug("serving cached page")
2021-12-07 18:36:57 -08:00
return ctx.HTMLBlob(page.StatusCode, page.HTML)
2021-12-07 18:36:57 -08:00
}
}
}
2021-12-21 17:49:05 -08:00
// CacheControl sets a Cache-Control header with a given max age
2021-12-06 11:53:28 -08:00
func CacheControl(maxAge time.Duration) echo.MiddlewareFunc {
2021-12-03 05:18:40 -08:00
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
2021-12-03 05:18:40 -08:00
v := "no-cache, no-store"
if maxAge > 0 {
2021-12-06 11:53:28 -08:00
v = fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds())
2021-12-03 05:18:40 -08:00
}
ctx.Response().Header().Set("Cache-Control", v)
return next(ctx)
2021-12-03 05:18:40 -08:00
}
}
}