Added gocache as a cache wrapper.

This commit is contained in:
mikestefanello 2021-12-06 14:53:28 -05:00
parent 70d9d0f8fa
commit 3a45695083
9 changed files with 212 additions and 29 deletions

View file

@ -2,6 +2,7 @@ package controllers
import (
"bytes"
"context"
"fmt"
"html/template"
"net/http"
@ -14,6 +15,8 @@ import (
"goweb/container"
"goweb/funcmap"
"github.com/eko/gocache/v2/store"
"github.com/labstack/echo/v4"
)
@ -56,21 +59,39 @@ func (t *Controller) RenderPage(c echo.Context, p Page) error {
return err
}
tmpl, ok := templates.Load(p.Name)
if !ok {
c.Logger().Error("Uncached page template requested")
return echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
}
buf := new(bytes.Buffer)
err := tmpl.(*template.Template).ExecuteTemplate(buf, p.Layout+TemplateExt, p)
buf, err := t.executeTemplates(c, p)
if err != nil {
return err
}
t.cachePage(c, p)
return c.HTMLBlob(p.StatusCode, buf.Bytes())
}
func (t *Controller) cachePage(c echo.Context, p Page) {
if !p.Cache.Enabled {
return
}
if p.Cache.MaxAge == 0 {
p.Cache.MaxAge = t.Container.Config.Cache.MaxAge.Page
}
ctx := context.Background() // TODO: make this real
key := c.Request().URL.String()
opts := &store.Options{
Expiration: p.Cache.MaxAge,
Tags: p.Cache.Tags,
}
err := t.Container.Cache.Set(ctx, key, "my-value", opts)
if err != nil {
c.Logger().Errorf("Failed to cache page: %s", key)
c.Logger().Error(err)
return
}
}
func (t *Controller) parsePageTemplates(p Page) error {
// 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
@ -100,6 +121,22 @@ func (t *Controller) parsePageTemplates(p Page) error {
return nil
}
func (t *Controller) executeTemplates(c echo.Context, p Page) (*bytes.Buffer, error) {
tmpl, ok := templates.Load(p.Name)
if !ok {
c.Logger().Error("Uncached page template requested")
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
}
buf := new(bytes.Buffer)
err := tmpl.(*template.Template).ExecuteTemplate(buf, p.Layout+TemplateExt, p)
if err != nil {
return nil, err
}
return buf, nil
}
func (t *Controller) Redirect(c echo.Context, route string, routeParams ...interface{}) error {
return c.Redirect(http.StatusFound, c.Echo().Reverse(route, routeParams))
}