saasitone/controller/controller.go

178 lines
5.0 KiB
Go
Raw Normal View History

package controller
2021-12-03 03:11:01 -08:00
import (
"bytes"
"fmt"
"net/http"
"github.com/mikestefanello/pagoda/context"
"github.com/mikestefanello/pagoda/htmx"
2022-01-01 07:44:18 -08:00
"github.com/mikestefanello/pagoda/middleware"
"github.com/mikestefanello/pagoda/services"
2021-12-03 03:11:01 -08:00
"github.com/labstack/echo/v4"
)
2021-12-19 07:03:42 -08:00
// Controller provides base functionality and dependencies to routes.
// The proposed pattern is to embed a Controller in each individual route struct and to use
// the router to inject the container so your routes have access to the services within the container
2021-12-03 03:11:01 -08:00
type Controller struct {
2021-12-19 07:03:42 -08:00
// Container stores a services container which contains dependencies
2021-12-18 07:07:12 -08:00
Container *services.Container
2021-12-03 03:11:01 -08:00
}
2021-12-19 07:03:42 -08:00
// NewController creates a new Controller
2021-12-18 07:07:12 -08:00
func NewController(c *services.Container) Controller {
2021-12-03 03:11:01 -08:00
return Controller{
Container: c,
}
}
2021-12-19 07:03:42 -08:00
// RenderPage renders a Page as an HTTP response
2021-12-19 17:14:00 -08:00
func (c *Controller) RenderPage(ctx echo.Context, page Page) error {
var buf *bytes.Buffer
var err error
2021-12-19 07:03:42 -08:00
// Page name is required
2021-12-19 17:14:00 -08:00
if page.Name == "" {
ctx.Logger().Error("page render failed due to missing name")
return echo.NewHTTPError(http.StatusInternalServerError)
2021-12-03 03:11:01 -08:00
}
2021-12-19 07:03:42 -08:00
// Use the app name in configuration if a value was not set
2021-12-19 17:14:00 -08:00
if page.AppName == "" {
page.AppName = c.Container.Config.App.Name
2021-12-03 03:11:01 -08:00
}
// 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 {
// Parse and execute the templates only for the content portion of the page
// The templates used for this partial request will be:
// 1. The base htmx template which omits the layout and only includes the content template
// 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 = c.Container.TemplateRenderer.
Parse().
Group("page:htmx").
Key(page.Name).
Base("htmx").
Files(
"htmx",
fmt.Sprintf("pages/%s", page.Name),
).
Directories("components").
Execute(page)
} else {
// 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 = c.Container.TemplateRenderer.
Parse().
Group("page").
Key(page.Name).
Base(page.Layout).
Files(
fmt.Sprintf("layouts/%s", page.Layout),
fmt.Sprintf("pages/%s", page.Name),
).
Directories("components").
Execute(page)
}
2021-12-03 03:11:01 -08:00
if err != nil {
ctx.Logger().Errorf("failed to parse and execute templates: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError)
2021-12-03 03:11:01 -08:00
}
// Set the status code
ctx.Response().Status = page.StatusCode
2021-12-07 18:36:57 -08:00
// Set any headers
2021-12-19 17:14:00 -08:00
for k, v := range page.Headers {
ctx.Response().Header().Set(k, v)
2021-12-07 18:36:57 -08:00
}
2021-12-06 11:53:28 -08:00
// Apply the HTMX response, if one
if page.HTMX.Response != nil {
page.HTMX.Response.Apply(ctx)
}
// Cache this page, if caching was enabled
c.cachePage(ctx, page, buf)
return ctx.HTMLBlob(ctx.Response().Status, buf.Bytes())
2021-12-03 03:11:01 -08:00
}
2021-12-19 07:03:42 -08:00
// cachePage caches the HTML for a given Page if the Page has caching enabled
2021-12-19 17:14:00 -08:00
func (c *Controller) cachePage(ctx echo.Context, page Page, html *bytes.Buffer) {
if !page.Cache.Enabled {
2021-12-06 11:53:28 -08:00
return
}
2021-12-19 07:03:42 -08:00
// If no expiration time was provided, default to the configuration value
2021-12-19 17:14:00 -08:00
if page.Cache.Expiration == 0 {
page.Cache.Expiration = c.Container.Config.Cache.Expiration.Page
2021-12-06 11:53:28 -08:00
}
// Extract the headers
headers := make(map[string]string)
for k, v := range ctx.Response().Header() {
headers[k] = v[0]
}
2021-12-19 07:03:42 -08:00
// The request URL is used as the cache key so the middleware can serve the
// cached page on matching requests
2021-12-19 17:14:00 -08:00
key := ctx.Request().URL.String()
2021-12-07 18:36:57 -08:00
cp := middleware.CachedPage{
2021-12-11 16:32:34 -08:00
URL: key,
2021-12-07 18:36:57 -08:00
HTML: html.Bytes(),
Headers: headers,
StatusCode: ctx.Response().Status,
2021-12-07 18:36:57 -08:00
}
2021-12-19 07:03:42 -08:00
err := c.Container.Cache.
Set().
Group(middleware.CachedPageGroup).
Key(key).
Tags(page.Cache.Tags...).
Expiration(page.Cache.Expiration).
Data(cp).
Save(ctx.Request().Context())
switch {
case err == nil:
ctx.Logger().Info("cached page")
case !context.IsCanceledError(err):
ctx.Logger().Errorf("failed to cache page: %v", err)
2021-12-06 11:53:28 -08:00
}
}
2021-12-19 07:03:42 -08:00
// Redirect redirects to a given route name with optional route parameters
2021-12-19 17:14:00 -08:00
func (c *Controller) Redirect(ctx echo.Context, route string, routeParams ...interface{}) error {
2021-12-23 20:04:00 -08:00
url := ctx.Echo().Reverse(route, routeParams)
if htmx.GetRequest(ctx).Boosted {
htmx.Response{
Redirect: url,
}.Apply(ctx)
return nil
} else {
2022-04-12 18:08:00 -07:00
return ctx.Redirect(http.StatusFound, url)
}
2021-12-03 03:11:01 -08:00
}
2021-12-05 17:22:45 -08:00
// Fail is a helper to fail a request by returning a 500 error and logging the error
2021-12-23 17:58:49 -08:00
func (c *Controller) Fail(ctx echo.Context, err error, log string) error {
if context.IsCanceledError(err) {
return nil
}
2021-12-23 17:58:49 -08:00
ctx.Logger().Errorf("%s: %v", log, err)
return echo.NewHTTPError(http.StatusInternalServerError)
}