Move controller to the template renderer (#68)
This commit is contained in:
parent
baa391fb20
commit
8eafb6b666
26 changed files with 654 additions and 679 deletions
|
|
@ -7,6 +7,7 @@ import (
|
|||
|
||||
"github.com/mikestefanello/pagoda/ent"
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/log"
|
||||
"github.com/mikestefanello/pagoda/pkg/msg"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
|
||||
|
|
@ -20,11 +21,10 @@ func LoadAuthenticatedUser(authClient *services.AuthClient) echo.MiddlewareFunc
|
|||
u, err := authClient.GetAuthenticatedUser(c)
|
||||
switch err.(type) {
|
||||
case *ent.NotFoundError:
|
||||
c.Logger().Warn("auth user not found")
|
||||
log.Ctx(c).Warn("auth user not found")
|
||||
case services.NotAuthenticatedError:
|
||||
case nil:
|
||||
c.Set(context.AuthenticatedUserKey, u)
|
||||
c.Logger().Infof("auth user loaded in to context: %d", u.ID)
|
||||
default:
|
||||
return echo.NewHTTPError(
|
||||
http.StatusInternalServerError,
|
||||
|
|
|
|||
|
|
@ -7,83 +7,56 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/context"
|
||||
"github.com/mikestefanello/pagoda/pkg/log"
|
||||
"github.com/mikestefanello/pagoda/pkg/services"
|
||||
|
||||
libstore "github.com/eko/gocache/lib/v4/store"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// CachedPageGroup stores the cache group for cached pages
|
||||
const CachedPageGroup = "page"
|
||||
|
||||
// CachedPage is what is used to store a rendered Page in the cache
|
||||
type CachedPage struct {
|
||||
// URL stores the URL of the requested page
|
||||
URL string
|
||||
|
||||
// HTML stores the complete HTML of the rendered Page
|
||||
HTML []byte
|
||||
|
||||
// StatusCode stores the HTTP status code
|
||||
StatusCode int
|
||||
|
||||
// Headers stores the HTTP headers
|
||||
Headers map[string]string
|
||||
}
|
||||
|
||||
// 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(ch *services.CacheClient) echo.MiddlewareFunc {
|
||||
func ServeCachedPage(t *services.TemplateRenderer) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
return func(ctx echo.Context) error {
|
||||
// Skip non GET requests
|
||||
if c.Request().Method != http.MethodGet {
|
||||
return next(c)
|
||||
if ctx.Request().Method != http.MethodGet {
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// Skip if the user is authenticated
|
||||
if c.Get(context.AuthenticatedUserKey) != nil {
|
||||
return next(c)
|
||||
if ctx.Get(context.AuthenticatedUserKey) != nil {
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// Attempt to load from cache
|
||||
res, err := ch.
|
||||
Get().
|
||||
Group(CachedPageGroup).
|
||||
Key(c.Request().URL.String()).
|
||||
Type(new(CachedPage)).
|
||||
Fetch(c.Request().Context())
|
||||
page, err := t.GetCachedPage(ctx, ctx.Request().URL.String())
|
||||
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, &libstore.NotFound{}):
|
||||
c.Logger().Info("no cached page found")
|
||||
case context.IsCanceledError(err):
|
||||
return nil
|
||||
default:
|
||||
c.Logger().Errorf("failed getting cached page: %v", err)
|
||||
log.Ctx(ctx).Error("failed getting cached page",
|
||||
"error", err,
|
||||
)
|
||||
}
|
||||
|
||||
return next(c)
|
||||
}
|
||||
|
||||
page, ok := res.(*CachedPage)
|
||||
if !ok {
|
||||
c.Logger().Errorf("failed casting cached page")
|
||||
return next(c)
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// Set any headers
|
||||
if page.Headers != nil {
|
||||
for k, v := range page.Headers {
|
||||
c.Response().Header().Set(k, v)
|
||||
ctx.Response().Header().Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
c.Logger().Info("serving cached page")
|
||||
log.Ctx(ctx).Debug("serving cached page")
|
||||
|
||||
return c.HTMLBlob(page.StatusCode, page.HTML)
|
||||
return ctx.HTMLBlob(page.StatusCode, page.HTML)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -91,13 +64,13 @@ func ServeCachedPage(ch *services.CacheClient) echo.MiddlewareFunc {
|
|||
// CacheControl sets a Cache-Control header with a given max age
|
||||
func CacheControl(maxAge time.Duration) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
return func(ctx echo.Context) error {
|
||||
v := "no-cache, no-store"
|
||||
if maxAge > 0 {
|
||||
v = fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds())
|
||||
}
|
||||
c.Response().Header().Set("Cache-Control", v)
|
||||
return next(c)
|
||||
ctx.Response().Header().Set("Cache-Control", v)
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mikestefanello/pagoda/pkg/page"
|
||||
"github.com/mikestefanello/pagoda/pkg/tests"
|
||||
"github.com/mikestefanello/pagoda/templates"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
|
|
@ -15,38 +16,34 @@ import (
|
|||
|
||||
func TestServeCachedPage(t *testing.T) {
|
||||
// Cache a page
|
||||
cp := CachedPage{
|
||||
URL: "/cache",
|
||||
HTML: []byte("html"),
|
||||
Headers: make(map[string]string),
|
||||
StatusCode: http.StatusCreated,
|
||||
}
|
||||
cp.Headers["a"] = "b"
|
||||
cp.Headers["c"] = "d"
|
||||
|
||||
err := c.Cache.
|
||||
Set().
|
||||
Group(CachedPageGroup).
|
||||
Key(cp.URL).
|
||||
Data(cp).
|
||||
Save(context.Background())
|
||||
ctx, rec := tests.NewContext(c.Web, "/cache")
|
||||
p := page.New(ctx)
|
||||
p.Layout = templates.LayoutHTMX
|
||||
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"
|
||||
err := c.TemplateRenderer.RenderPage(ctx, p)
|
||||
output := rec.Body.Bytes()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Request the URL of the cached page
|
||||
ctx, rec := tests.NewContext(c.Web, cp.URL)
|
||||
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.Cache))
|
||||
ctx, rec = tests.NewContext(c.Web, "/cache")
|
||||
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.TemplateRenderer))
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, cp.StatusCode, ctx.Response().Status)
|
||||
assert.Equal(t, cp.Headers["a"], ctx.Response().Header().Get("a"))
|
||||
assert.Equal(t, cp.Headers["c"], ctx.Response().Header().Get("c"))
|
||||
assert.Equal(t, cp.HTML, rec.Body.Bytes())
|
||||
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.Cache))
|
||||
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.TemplateRenderer))
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue