Migrate from templates to Gomponents (#103)

This commit is contained in:
Mike Stefanello 2025-03-05 20:01:58 -05:00 committed by GitHub
parent 0bf9ab7189
commit 051d032038
104 changed files with 2768 additions and 2824 deletions

View file

@ -16,51 +16,47 @@ import (
_ "github.com/mattn/go-sqlite3"
"github.com/mikestefanello/pagoda/config"
"github.com/mikestefanello/pagoda/ent"
"github.com/mikestefanello/pagoda/pkg/funcmap"
"github.com/mikestefanello/pagoda/pkg/log"
// Require by ent
// Required by ent.
_ "github.com/mikestefanello/pagoda/ent/runtime"
)
// Container contains all services used by the application and provides an easy way to handle dependency
// injection including within tests
// injection including within tests.
type Container struct {
// Validator stores a validator
Validator *Validator
// Web stores the web framework
// Web stores the web framework.
Web *echo.Echo
// Config stores the application configuration
// Config stores the application configuration.
Config *config.Config
// Cache contains the cache client
// Cache contains the cache client.
Cache *CacheClient
// Database stores the connection to the database
// Database stores the connection to the database.
Database *sql.DB
// Files stores the file system.
Files afero.Fs
// ORM stores a client to the ORM
// ORM stores a client to the ORM.
ORM *ent.Client
// Mail stores an email sending client
// Mail stores an email sending client.
Mail *MailClient
// Auth stores an authentication client
// Auth stores an authentication client.
Auth *AuthClient
// TemplateRenderer stores a service to easily render and cache templates
TemplateRenderer *TemplateRenderer
// Tasks stores the task client
// Tasks stores the task client.
Tasks *backlite.Client
}
// NewContainer creates and initializes a new Container
// NewContainer creates and initializes a new Container.
func NewContainer() *Container {
c := new(Container)
c.initConfig()
@ -71,7 +67,6 @@ func NewContainer() *Container {
c.initFiles()
c.initORM()
c.initAuth()
c.initTemplateRenderer()
c.initMail()
c.initTasks()
return c
@ -107,7 +102,7 @@ func (c *Container) Shutdown() error {
return nil
}
// initConfig initializes configuration
// initConfig initializes configuration.
func (c *Container) initConfig() {
cfg, err := config.GetConfig()
if err != nil {
@ -115,7 +110,7 @@ func (c *Container) initConfig() {
}
c.Config = &cfg
// Configure logging
// Configure logging.
switch cfg.App.Environment {
case config.EnvProduction:
slog.SetLogLoggerLevel(slog.LevelInfo)
@ -124,19 +119,19 @@ func (c *Container) initConfig() {
}
}
// initValidator initializes the validator
// initValidator initializes the validator.
func (c *Container) initValidator() {
c.Validator = NewValidator()
}
// initWeb initializes the web framework
// initWeb initializes the web framework.
func (c *Container) initWeb() {
c.Web = echo.New()
c.Web.HideBanner = true
c.Web.Validator = c.Validator
}
// initCache initializes the cache
// initCache initializes the cache.
func (c *Container) initCache() {
store, err := newInMemoryCache(c.Config.Cache.Capacity)
if err != nil {
@ -146,7 +141,7 @@ func (c *Container) initCache() {
c.Cache = NewCacheClient(store)
}
// initDatabase initializes the database
// initDatabase initializes the database.
func (c *Container) initDatabase() {
var err error
var connection string
@ -180,7 +175,7 @@ func (c *Container) initFiles() {
c.Files = afero.NewBasePathFs(fs, c.Config.Files.Directory)
}
// initORM initializes the ORM
// initORM initializes the ORM.
func (c *Container) initORM() {
drv := entsql.OpenDB(c.Config.Database.Driver, c.Database)
c.ORM = ent.NewClient(ent.Driver(drv))
@ -191,30 +186,25 @@ func (c *Container) initORM() {
}
}
// initAuth initializes the authentication client
// initAuth initializes the authentication client.
func (c *Container) initAuth() {
c.Auth = NewAuthClient(c.Config, c.ORM)
}
// initTemplateRenderer initializes the template renderer
func (c *Container) initTemplateRenderer() {
c.TemplateRenderer = NewTemplateRenderer(c.Config, c.Cache, funcmap.NewFuncMap(c.Web))
}
// initMail initialize the mail client
// initMail initialize the mail client.
func (c *Container) initMail() {
var err error
c.Mail, err = NewMailClient(c.Config, c.TemplateRenderer)
c.Mail, err = NewMailClient(c.Config)
if err != nil {
panic(fmt.Sprintf("failed to create mail client: %v", err))
}
}
// initTasks initializes the task client
// initTasks initializes the task client.
func (c *Container) initTasks() {
var err error
// You could use a separate database for tasks, if you'd like. but using one
// makes transaction support easier
// makes transaction support easier.
c.Tasks, err = backlite.NewClient(backlite.ClientConfig{
DB: c.Database,
Logger: log.Default(),
@ -232,10 +222,10 @@ func (c *Container) initTasks() {
}
}
// openDB opens a database connection
// openDB opens a database connection.
func openDB(driver, connection string) (*sql.DB, error) {
// Helper to automatically create the directories that the specified sqlite file
// should reside in, if one
// should reside in, if one.
if driver == "sqlite3" {
d := strings.Split(connection, "/")

View file

@ -16,6 +16,5 @@ func TestNewContainer(t *testing.T) {
assert.NotNil(t, c.ORM)
assert.NotNil(t, c.Mail)
assert.NotNil(t, c.Auth)
assert.NotNil(t, c.TemplateRenderer)
assert.NotNil(t, c.Tasks)
}

View file

@ -1,11 +1,12 @@
package services
import (
"bytes"
"errors"
"fmt"
"github.com/mikestefanello/pagoda/config"
"github.com/mikestefanello/pagoda/pkg/log"
"maragu.dev/gomponents"
"github.com/labstack/echo/v4"
)
@ -14,36 +15,31 @@ type (
// MailClient provides a client for sending email
// This is purposely not completed because there are many different methods and services
// for sending email, many of which are very different. Choose what works best for you
// and populate the methods below
// and populate the methods below. For now, emails will just be logged.
MailClient struct {
// config stores application configuration
// config stores application configuration.
config *config.Config
// templates stores the template renderer
templates *TemplateRenderer
}
// mail represents an email to be sent
// mail represents an email to be sent.
mail struct {
client *MailClient
from string
to string
subject string
body string
template string
templateData any
client *MailClient
from string
to string
subject string
body string
component gomponents.Node
}
)
// NewMailClient creates a new MailClient
func NewMailClient(cfg *config.Config, templates *TemplateRenderer) (*MailClient, error) {
// NewMailClient creates a new MailClient.
func NewMailClient(cfg *config.Config) (*MailClient, error) {
return &MailClient{
config: cfg,
templates: templates,
config: cfg,
}, nil
}
// Compose creates a new email
// Compose creates a new email.
func (m *MailClient) Compose() *mail {
return &mail{
client: m,
@ -51,39 +47,33 @@ func (m *MailClient) Compose() *mail {
}
}
// skipSend determines if mail sending should be skipped
// skipSend determines if mail sending should be skipped.
func (m *MailClient) skipSend() bool {
return m.config.App.Environment != config.EnvProduction
}
// send attempts to send the email
// send attempts to send the email.
func (m *MailClient) send(email *mail, ctx echo.Context) error {
switch {
case email.to == "":
return errors.New("email cannot be sent without a to address")
case email.body == "" && email.template == "":
return errors.New("email cannot be sent without a body or template")
case email.body == "" && email.component == nil:
return errors.New("email cannot be sent without a body or component to render")
}
// Check if a template was supplied
if email.template != "" {
// Parse and execute template
buf, err := m.templates.
Parse().
Group("mail").
Key(email.template).
Base(email.template).
Files(fmt.Sprintf("emails/%s", email.template)).
Execute(email.templateData)
if err != nil {
// Check if a component was supplied.
if email.component != nil {
// Render the component and use as the body.
// TODO pool the buffers?
buf := bytes.NewBuffer(nil)
if err := email.component.Render(buf); err != nil {
return err
}
email.body = buf.String()
}
// Check if mail sending should be skipped
// Check if mail sending should be skipped.
if m.skipSend() {
log.Ctx(ctx).Debug("skipping email delivery",
"to", email.to,
@ -91,52 +81,47 @@ func (m *MailClient) send(email *mail, ctx echo.Context) error {
return nil
}
// TODO: Finish based on your mail sender of choice!
// TODO: Finish based on your mail sender of choice or stop logging below!
log.Ctx(ctx).Info("sending email",
"to", email.to,
"subject", email.subject,
"body", email.body,
)
return nil
}
// From sets the email from address
// From sets the email from address.
func (m *mail) From(from string) *mail {
m.from = from
return m
}
// To sets the email address this email will be sent to
// To sets the email address this email will be sent to.
func (m *mail) To(to string) *mail {
m.to = to
return m
}
// Subject sets the subject line of the email
// Subject sets the subject line of the email.
func (m *mail) Subject(subject string) *mail {
m.subject = subject
return m
}
// Body sets the body of the email
// This is not required and will be ignored if a template via Template()
// Body sets the body of the email.
// This is not required and will be ignored if a component is set via Component().
func (m *mail) Body(body string) *mail {
m.body = body
return m
}
// Template sets the template to be used to produce the body of the email
// The template name should only include the filename without the extension or directory.
// The template must reside within the emails sub-directory.
// The funcmap will be automatically added to the template.
// Use TemplateData() to supply the data that will be passed in to the template.
func (m *mail) Template(template string) *mail {
m.template = template
// Component sets a renderable component to use as the body of the email.
func (m *mail) Component(component gomponents.Node) *mail {
m.component = component
return m
}
// TemplateData sets the data that will be passed to the template specified when calling Template()
func (m *mail) TemplateData(data any) *mail {
m.templateData = data
return m
}
// Send attempts to send the email
// Send attempts to send the email.
func (m *mail) Send(ctx echo.Context) error {
return m.client.send(m, ctx)
}

View file

@ -1,376 +0,0 @@
package services
import (
"bytes"
"errors"
"fmt"
"html/template"
"io/fs"
"net/http"
"sync"
"github.com/labstack/echo/v4"
"github.com/mikestefanello/pagoda/config"
"github.com/mikestefanello/pagoda/pkg/context"
"github.com/mikestefanello/pagoda/pkg/log"
"github.com/mikestefanello/pagoda/pkg/page"
"github.com/mikestefanello/pagoda/templates"
)
// cachedPageGroup stores the cache group for cached pages
const cachedPageGroup = "page"
type (
// TemplateRenderer provides a flexible and easy to use method of rendering simple templates or complex sets of
// templates while also providing caching and/or hot-reloading depending on your current environment
TemplateRenderer struct {
// templateCache stores a cache of parsed page templates
templateCache sync.Map
// funcMap stores the template function map
funcMap template.FuncMap
// config stores application configuration
config *config.Config
// cache stores the cache client
cache *CacheClient
}
// TemplateParsed is a wrapper around parsed templates which are stored in the TemplateRenderer cache
TemplateParsed struct {
// Template is the parsed template
Template *template.Template
// build stores the build data used to parse the template
build *templateBuild
}
// templateBuild stores the build data used to parse a template
templateBuild struct {
group string
key string
base string
files []string
directories []string
}
// templateBuilder handles chaining a template parse operation
templateBuilder struct {
build *templateBuild
renderer *TemplateRenderer
}
// CachedPage is what is used to store a rendered Page in the cache
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
}
)
// NewTemplateRenderer creates a new TemplateRenderer
func NewTemplateRenderer(cfg *config.Config, cache *CacheClient, fm template.FuncMap) *TemplateRenderer {
return &TemplateRenderer{
templateCache: sync.Map{},
funcMap: fm,
config: cfg,
cache: cache,
}
}
// Parse creates a template build operation
func (t *TemplateRenderer) Parse() *templateBuilder {
return &templateBuilder{
renderer: t,
build: &templateBuild{},
}
}
// RenderPage renders a Page as an HTTP response
func (t *TemplateRenderer) RenderPage(ctx echo.Context, page page.Page) error {
var buf *bytes.Buffer
var err error
templateGroup := "page"
// Page name is required
if page.Name == "" {
return echo.NewHTTPError(http.StatusInternalServerError, "page render failed due to missing name")
}
// Use the app name in configuration if a value was not set
if page.AppName == "" {
page.AppName = t.config.App.Name
}
// Check if this is an HTMX non-boosted request which indicates that only partial
// content should be rendered
if page.HTMX.Request.Enabled && !page.HTMX.Request.Boosted {
// Switch the layout which will only render the page content
page.Layout = templates.LayoutHTMX
// Alter the template group so this is cached separately
templateGroup = "page:htmx"
}
// Parse and execute the templates for the Page
// As mentioned in the documentation for the Page struct, the templates used for the page will be:
// 1. The layout/base template specified in Page.Layout
// 2. The content template specified in Page.Name
// 3. All templates within the components directory
// Also included is the function map provided by the funcmap package
buf, err = t.
Parse().
Group(templateGroup).
Key(string(page.Name)).
Base(string(page.Layout)).
Files(
fmt.Sprintf("layouts/%s", page.Layout),
fmt.Sprintf("pages/%s", page.Name),
).
Directories("components").
Execute(page)
if err != nil {
return echo.NewHTTPError(
http.StatusInternalServerError,
fmt.Sprintf("failed to parse and execute templates: %s", err),
)
}
// Set the status code
ctx.Response().Status = page.StatusCode
// Set any headers
for k, v := range page.Headers {
ctx.Response().Header().Set(k, v)
}
// Apply the HTMX response, if one
if page.HTMX.Response != nil {
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())
}
// 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
func (t *TemplateRenderer) getCacheKey(group, key string) string {
if group != "" {
return fmt.Sprintf("%s:%s", group, key)
}
return key
}
// parse parses a set of templates and caches them for quick execution
// If the application environment is set to local, the cache will be bypassed and templates will be
// parsed upon each request so hot-reloading is possible without restarts.
// Also included will be the function map provided by the funcmap package.
func (t *TemplateRenderer) parse(build *templateBuild) (*TemplateParsed, error) {
var tp *TemplateParsed
var err error
switch {
case build.key == "":
return nil, errors.New("cannot parse template without key")
case len(build.files) == 0 && len(build.directories) == 0:
return nil, errors.New("cannot parse template without files or directories")
case build.base == "":
return nil, errors.New("cannot parse template without base")
}
// Generate the cache key
cacheKey := t.getCacheKey(build.group, build.key)
// Check if the template has not yet been parsed or if the app environment is local, so that
// templates reflect changes without having the restart the server
if tp, err = t.Load(build.group, build.key); err != nil || t.config.App.Environment == config.EnvLocal {
// Initialize the parsed template with the function map
parsed := template.New(build.base + config.TemplateExt).
Funcs(t.funcMap)
// Format the requested files
for k, v := range build.files {
build.files[k] = fmt.Sprintf("%s%s", v, config.TemplateExt)
}
// Include all files within the requested directories
for k, v := range build.directories {
build.directories[k] = fmt.Sprintf("%s/*%s", v, config.TemplateExt)
}
// Get the templates
var tpl fs.FS
if t.config.App.Environment == config.EnvLocal {
tpl = templates.GetOS()
} else {
tpl = templates.Get()
}
// Parse the templates
parsed, err = parsed.ParseFS(tpl, append(build.files, build.directories...)...)
if err != nil {
return nil, err
}
// Store the template so this process only happens once
tp = &TemplateParsed{
Template: parsed,
build: build,
}
t.templateCache.Store(cacheKey, tp)
}
return tp, nil
}
// Load loads a template from the cache
func (t *TemplateRenderer) Load(group, key string) (*TemplateParsed, error) {
load, ok := t.templateCache.Load(t.getCacheKey(group, key))
if !ok {
return nil, errors.New("uncached page template requested")
}
tmpl, ok := load.(*TemplateParsed)
if !ok {
return nil, errors.New("unable to cast cached template")
}
return tmpl, nil
}
// Execute executes a template with the given data and provides the output
func (t *TemplateParsed) Execute(data any) (*bytes.Buffer, error) {
if t.Template == nil {
return nil, errors.New("cannot execute template: template not initialized")
}
buf := new(bytes.Buffer)
err := t.Template.ExecuteTemplate(buf, t.build.base+config.TemplateExt, data)
if err != nil {
return nil, err
}
return buf, nil
}
// Group sets the cache group for the template being built
func (t *templateBuilder) Group(group string) *templateBuilder {
t.build.group = group
return t
}
// Key sets the cache key for the template being built
func (t *templateBuilder) Key(key string) *templateBuilder {
t.build.key = key
return t
}
// Base sets the name of the base template to be used during template parsing and execution.
// This should be only the file name without a directory or extension.
func (t *templateBuilder) Base(base string) *templateBuilder {
t.build.base = base
return t
}
// Files sets a list of template files to include in the parse.
// This should not include the file extension and the paths should be relative to the templates directory.
func (t *templateBuilder) Files(files ...string) *templateBuilder {
t.build.files = files
return t
}
// Directories sets a list of directories that all template files within will be parsed.
// The paths should be relative to the templates directory.
func (t *templateBuilder) Directories(directories ...string) *templateBuilder {
t.build.directories = directories
return t
}
// Store parsed the templates and stores them in the cache
func (t *templateBuilder) Store() (*TemplateParsed, error) {
return t.renderer.parse(t.build)
}
// Execute executes the template with the given data.
// If the template has not already been cached, this will parse and cache the template
func (t *templateBuilder) Execute(data any) (*bytes.Buffer, error) {
tp, err := t.Store()
if err != nil {
return nil, err
}
return tp.Execute(data)
}

View file

@ -1,198 +0,0 @@
package services
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/mikestefanello/pagoda/config"
"github.com/mikestefanello/pagoda/pkg/htmx"
"github.com/mikestefanello/pagoda/pkg/page"
"github.com/mikestefanello/pagoda/pkg/tests"
"github.com/mikestefanello/pagoda/templates"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTemplateRenderer(t *testing.T) {
group := "test"
id := "parse"
// Should not exist yet
_, err := c.TemplateRenderer.Load(group, id)
assert.Error(t, err)
// Parse in to the cache
tpl, err := c.TemplateRenderer.
Parse().
Group(group).
Key(id).
Base("htmx").
Files("layouts/htmx", "pages/error").
Directories("components").
Store()
require.NoError(t, err)
// Should exist now
parsed, err := c.TemplateRenderer.Load(group, id)
require.NoError(t, err)
// Check that all expected templates are included
expectedTemplates := make(map[string]bool)
expectedTemplates["htmx"+config.TemplateExt] = true
expectedTemplates["error"+config.TemplateExt] = true
components, err := templates.Get().ReadDir("components")
require.NoError(t, err)
for _, f := range components {
expectedTemplates[f.Name()] = true
}
for _, v := range parsed.Template.Templates() {
delete(expectedTemplates, v.Name())
}
assert.Empty(t, expectedTemplates)
data := struct {
StatusCode int
}{
StatusCode: 500,
}
buf, err := tpl.Execute(data)
require.NoError(t, err)
require.NotNil(t, buf)
assert.Contains(t, buf.String(), "Please try again")
buf, err = c.TemplateRenderer.
Parse().
Group(group).
Key(id).
Base("htmx").
Files("htmx", "pages/error").
Directories("components").
Execute(data)
require.NoError(t, err)
require.NotNil(t, buf)
assert.Contains(t, buf.String(), "Please try again")
}
func TestTemplateRenderer_RenderPage(t *testing.T) {
setup := func() (echo.Context, *httptest.ResponseRecorder, page.Page) {
ctx, rec := tests.NewContext(c.Web, "/test/TestTemplateRenderer_RenderPage")
tests.InitSession(ctx)
p := page.New(ctx)
p.Name = "home"
p.Layout = "main"
p.Cache.Enabled = false
p.Headers["A"] = "b"
p.Headers["C"] = "d"
p.StatusCode = http.StatusCreated
return ctx, rec, p
}
t.Run("missing name", func(t *testing.T) {
// Rendering should fail if the Page has no name
ctx, _, p := setup()
p.Name = ""
err := c.TemplateRenderer.RenderPage(ctx, p)
assert.Error(t, err)
})
t.Run("no page cache", func(t *testing.T) {
ctx, _, p := setup()
err := c.TemplateRenderer.RenderPage(ctx, p)
require.NoError(t, err)
// Check status code and headers
assert.Equal(t, http.StatusCreated, ctx.Response().Status)
for k, v := range p.Headers {
assert.Equal(t, v, ctx.Response().Header().Get(k))
}
// Check the template cache
parsed, err := c.TemplateRenderer.Load("page", string(p.Name))
require.NoError(t, err)
// Check that all expected templates were parsed.
// This includes the name, layout and all components
expectedTemplates := make(map[string]bool)
expectedTemplates[fmt.Sprintf("%s%s", p.Name, config.TemplateExt)] = true
expectedTemplates[fmt.Sprintf("%s%s", p.Layout, config.TemplateExt)] = true
components, err := templates.Get().ReadDir("components")
require.NoError(t, err)
for _, f := range components {
expectedTemplates[f.Name()] = true
}
for _, v := range parsed.Template.Templates() {
delete(expectedTemplates, v.Name())
}
assert.Empty(t, expectedTemplates)
})
t.Run("htmx rendering", func(t *testing.T) {
ctx, _, p := setup()
p.HTMX.Request.Enabled = true
p.HTMX.Response = &htmx.Response{
Trigger: "trigger",
}
err := c.TemplateRenderer.RenderPage(ctx, p)
require.NoError(t, err)
// Check HTMX header
assert.Equal(t, "trigger", ctx.Response().Header().Get(htmx.HeaderTrigger))
// Check the template cache
parsed, err := c.TemplateRenderer.Load("page:htmx", string(p.Name))
require.NoError(t, err)
// Check that all expected templates were parsed.
// This includes the name, htmx and all components
expectedTemplates := make(map[string]bool)
expectedTemplates[fmt.Sprintf("%s%s", p.Name, config.TemplateExt)] = true
expectedTemplates["htmx"+config.TemplateExt] = true
components, err := templates.Get().ReadDir("components")
require.NoError(t, err)
for _, f := range components {
expectedTemplates[f.Name()] = true
}
for _, v := range parsed.Template.Templates() {
delete(expectedTemplates, v.Name())
}
assert.Empty(t, expectedTemplates)
})
t.Run("page cache", func(t *testing.T) {
ctx, rec, p := setup()
p.Cache.Enabled = true
p.Cache.Tags = []string{"tag1"}
err := c.TemplateRenderer.RenderPage(ctx, p)
require.NoError(t, err)
// Fetch from the cache
cp, err := c.TemplateRenderer.GetCachedPage(ctx, p.URL)
require.NoError(t, err)
// Compare the cached page
assert.Equal(t, p.URL, cp.URL)
assert.Equal(t, p.Headers, cp.Headers)
assert.Equal(t, p.StatusCode, cp.StatusCode)
assert.Equal(t, rec.Body.Bytes(), cp.HTML)
// Clear the tag
err = c.Cache.
Flush().
Tags(p.Cache.Tags[0]).
Execute(context.Background())
require.NoError(t, err)
// Refetch from the cache and expect no results
_, err = c.TemplateRenderer.GetCachedPage(ctx, p.URL)
assert.Error(t, err)
})
}