Compare commits
2 Commits
a382f1da69
...
e3e37a6db8
Author | SHA1 | Date | |
---|---|---|---|
e3e37a6db8 | |||
1cf2971bdc |
@ -90,6 +90,7 @@
|
|||||||
* [Logging](#logging)
|
* [Logging](#logging)
|
||||||
* [Roadmap](#roadmap)
|
* [Roadmap](#roadmap)
|
||||||
* [Credits](#credits)
|
* [Credits](#credits)
|
||||||
|
* [Similar Projects](#similar-projects)
|
||||||
|
|
||||||
## Introduction
|
## Introduction
|
||||||
|
|
||||||
@ -1187,3 +1188,8 @@ Thank you to all of the following amazing projects for making this possible.
|
|||||||
- [testify](https://github.com/stretchr/testify)
|
- [testify](https://github.com/stretchr/testify)
|
||||||
- [validator](https://github.com/go-playground/validator)
|
- [validator](https://github.com/go-playground/validator)
|
||||||
- [viper](https://github.com/spf13/viper)
|
- [viper](https://github.com/spf13/viper)
|
||||||
|
|
||||||
|
## Similar Projects
|
||||||
|
|
||||||
|
- [go-templ-htmx-templ](https://github.com/HoneySinghDev/go-templ-htmx-template)
|
||||||
|
- [go-webly](https://github.com/gowebly/gowebly)
|
||||||
|
@ -42,6 +42,7 @@ func BuildRouter(c *services.Container) error {
|
|||||||
}),
|
}),
|
||||||
middleware.Session(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))),
|
middleware.Session(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))),
|
||||||
middleware.LoadAuthenticatedUser(c.Auth),
|
middleware.LoadAuthenticatedUser(c.Auth),
|
||||||
|
middleware.ServeCachedPage(c.TemplateRenderer),
|
||||||
echomw.CSRFWithConfig(echomw.CSRFConfig{
|
echomw.CSRFWithConfig(echomw.CSRFConfig{
|
||||||
TokenLookup: "form:csrf",
|
TokenLookup: "form:csrf",
|
||||||
}),
|
}),
|
||||||
|
@ -1,12 +1,64 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/pkg/context"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/pkg/log"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attempt to load from cache
|
||||||
|
page, err := t.GetCachedPage(ctx, ctx.Request().URL.String())
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return next(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set any headers
|
||||||
|
if page.Headers != nil {
|
||||||
|
for k, v := range page.Headers {
|
||||||
|
ctx.Response().Header().Set(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Ctx(ctx).Debug("serving cached page")
|
||||||
|
|
||||||
|
return ctx.HTMLBlob(page.StatusCode, page.HTML)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// CacheControl sets a Cache-Control header with a given max age
|
// CacheControl sets a Cache-Control header with a given max age
|
||||||
func CacheControl(maxAge time.Duration) echo.MiddlewareFunc {
|
func CacheControl(maxAge time.Duration) echo.MiddlewareFunc {
|
||||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
|
@ -1,14 +1,56 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/a-h/templ"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
|
||||||
"git.grosinger.net/tgrosinger/saasitone/pkg/tests"
|
"git.grosinger.net/tgrosinger/saasitone/pkg/tests"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/templates"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestServeCachedPage(t *testing.T) {
|
||||||
|
// Cache a page
|
||||||
|
ctx, rec := tests.NewContext(c.Web, "/cache")
|
||||||
|
p := page.New(ctx)
|
||||||
|
p.Name = templates.PageHome
|
||||||
|
p.Cache.Enabled = true
|
||||||
|
p.Cache.Expiration = time.Minute
|
||||||
|
p.StatusCode = http.StatusCreated
|
||||||
|
p.Headers["a"] = "b"
|
||||||
|
p.Headers["c"] = "d"
|
||||||
|
p.LayoutComponent = func(content templ.Component) templ.Component {
|
||||||
|
return layouts.HTMX(p, content)
|
||||||
|
}
|
||||||
|
err := c.TemplateRenderer.RenderPageTempl(ctx, p, pages.Cache(p, &pages.CacheForm{}, nil))
|
||||||
|
output := rec.Body.Bytes()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Request the URL of the cached page
|
||||||
|
ctx, rec = tests.NewContext(c.Web, "/cache")
|
||||||
|
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.TemplateRenderer))
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, p.StatusCode, ctx.Response().Status)
|
||||||
|
assert.Equal(t, p.Headers["a"], ctx.Response().Header().Get("a"))
|
||||||
|
assert.Equal(t, p.Headers["c"], ctx.Response().Header().Get("c"))
|
||||||
|
assert.Equal(t, output, rec.Body.Bytes())
|
||||||
|
|
||||||
|
// Login and try again
|
||||||
|
tests.InitSession(ctx)
|
||||||
|
err = c.Auth.Login(ctx, usr.ID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
_ = tests.ExecuteMiddleware(ctx, LoadAuthenticatedUser(c.Auth))
|
||||||
|
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.TemplateRenderer))
|
||||||
|
assert.Nil(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
func TestCacheControl(t *testing.T) {
|
func TestCacheControl(t *testing.T) {
|
||||||
ctx, _ := tests.NewContext(c.Web, "/")
|
ctx, _ := tests.NewContext(c.Web, "/")
|
||||||
_ = tests.ExecuteMiddleware(ctx, CacheControl(time.Second*5))
|
_ = tests.ExecuteMiddleware(ctx, CacheControl(time.Second*5))
|
||||||
|
@ -13,6 +13,8 @@ import (
|
|||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
"git.grosinger.net/tgrosinger/saasitone/config"
|
"git.grosinger.net/tgrosinger/saasitone/config"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/pkg/context"
|
||||||
|
"git.grosinger.net/tgrosinger/saasitone/pkg/log"
|
||||||
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
|
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
|
||||||
"git.grosinger.net/tgrosinger/saasitone/templates"
|
"git.grosinger.net/tgrosinger/saasitone/templates"
|
||||||
)
|
)
|
||||||
@ -135,9 +137,70 @@ func (t *TemplateRenderer) RenderPageTempl(ctx echo.Context, page page.Page, con
|
|||||||
page.HTMX.Response.Apply(ctx)
|
page.HTMX.Response.Apply(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cache this page, if caching was enabled
|
||||||
|
t.cachePage(ctx, page, &buf)
|
||||||
return ctx.HTMLBlob(ctx.Response().Status, buf.Bytes())
|
return ctx.HTMLBlob(ctx.Response().Status, buf.Bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cachePage caches the HTML for a given Page if the Page has caching enabled
|
||||||
|
func (t *TemplateRenderer) cachePage(ctx echo.Context, page page.Page, html *bytes.Buffer) {
|
||||||
|
if !page.Cache.Enabled || page.IsAuth {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no expiration time was provided, default to the configuration value
|
||||||
|
if page.Cache.Expiration == 0 {
|
||||||
|
page.Cache.Expiration = t.config.Cache.Expiration.Page
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract the headers
|
||||||
|
headers := make(map[string]string)
|
||||||
|
for k, v := range ctx.Response().Header() {
|
||||||
|
headers[k] = v[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// The request URL is used as the cache key so the middleware can serve the
|
||||||
|
// cached page on matching requests
|
||||||
|
key := ctx.Request().URL.String()
|
||||||
|
cp := &CachedPage{
|
||||||
|
URL: key,
|
||||||
|
HTML: html.Bytes(),
|
||||||
|
Headers: headers,
|
||||||
|
StatusCode: ctx.Response().Status,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := t.cache.
|
||||||
|
Set().
|
||||||
|
Group(cachedPageGroup).
|
||||||
|
Key(key).
|
||||||
|
Tags(page.Cache.Tags...).
|
||||||
|
Expiration(page.Cache.Expiration).
|
||||||
|
Data(cp).
|
||||||
|
Save(ctx.Request().Context())
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
log.Ctx(ctx).Debug("cached page")
|
||||||
|
case !context.IsCanceledError(err):
|
||||||
|
log.Ctx(ctx).Error("failed to cache page",
|
||||||
|
"error", err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCachedPage attempts to fetch a cached page for a given URL
|
||||||
|
func (t *TemplateRenderer) GetCachedPage(ctx echo.Context, url string) (*CachedPage, error) {
|
||||||
|
p, err := t.cache.
|
||||||
|
Get().
|
||||||
|
Group(cachedPageGroup).
|
||||||
|
Key(url).
|
||||||
|
Fetch(ctx.Request().Context())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return p.(*CachedPage), nil
|
||||||
|
}
|
||||||
// getCacheKey gets a cache key for a given group and ID
|
// getCacheKey gets a cache key for a given group and ID
|
||||||
func (t *TemplateRenderer) getCacheKey(group, key string) string {
|
func (t *TemplateRenderer) getCacheKey(group, key string) string {
|
||||||
if group != "" {
|
if group != "" {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user