saasitone/controller/controller.go

181 lines
5.8 KiB
Go
Raw Normal View History

package controller
2021-12-03 03:11:01 -08:00
import (
"bytes"
"fmt"
"net/http"
"reflect"
2021-12-03 03:11:01 -08:00
2021-12-07 18:36:57 -08:00
"goweb/middleware"
"goweb/msg"
2021-12-18 07:07:12 -08:00
"goweb/services"
"github.com/go-playground/validator/v10"
2021-12-07 18:36:57 -08:00
"github.com/eko/gocache/v2/marshaler"
2021-12-03 03:11:01 -08:00
2021-12-06 11:53:28 -08:00
"github.com/eko/gocache/v2/store"
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 {
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")
2021-12-03 03:11:01 -08:00
return echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
}
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
}
2021-12-19 07:03:42 -08:00
// Parse the templates in the page and store them in a cache, if not yet done
2021-12-19 17:14:00 -08:00
if err := c.parsePageTemplates(page); err != nil {
ctx.Logger().Errorf("failed to parse templates: %v", err)
2021-12-19 07:03:42 -08:00
return echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
2021-12-03 03:11:01 -08:00
}
2021-12-19 07:03:42 -08:00
// Execute the parsed templates to render the page
2021-12-19 17:14:00 -08:00
buf, err := c.executeTemplates(page)
2021-12-03 03:11:01 -08:00
if err != nil {
2021-12-19 17:14:00 -08:00
ctx.Logger().Errorf("failed to execute templates: %v", err)
2021-12-19 07:03:42 -08:00
return echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
2021-12-03 03:11:01 -08:00
}
2021-12-19 07:03:42 -08:00
// Cache this page, if caching was enabled
2021-12-19 17:14:00 -08:00
c.cachePage(ctx, page, buf)
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
2021-12-19 17:14:00 -08:00
return ctx.HTMLBlob(page.StatusCode, 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
}
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-06 11:53:28 -08:00
opts := &store.Options{
2021-12-19 17:14:00 -08:00
Expiration: page.Cache.Expiration,
Tags: page.Cache.Tags,
2021-12-06 11:53:28 -08:00
}
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(),
2021-12-19 17:14:00 -08:00
Headers: page.Headers,
StatusCode: page.StatusCode,
2021-12-07 18:36:57 -08:00
}
2021-12-19 07:03:42 -08:00
2021-12-19 17:14:00 -08:00
err := marshaler.New(c.Container.Cache).Set(ctx.Request().Context(), key, cp, opts)
2021-12-06 11:53:28 -08:00
if err != nil {
2021-12-19 17:14:00 -08:00
ctx.Logger().Errorf("failed to cache page: %v", err)
2021-12-06 11:53:28 -08:00
return
}
2021-12-07 18:36:57 -08:00
2021-12-19 17:14:00 -08:00
ctx.Logger().Infof("cached page")
2021-12-06 11:53:28 -08:00
}
2021-12-19 07:03:42 -08:00
// parsePageTemplates parses the templates for the given Page and caches them to avoid duplicate operations
// If the configuration indicates that the environment is local, the cache is bypassed for template changes
// can be seen without having to restart the application.
// As mentioned in the documentation for the Page struct, the templates used for the page will be:
// 1. The layout/based template specified in Page.Layout
// 2. The content template specified in Page.Name
// 3. All templates within the components directory
2021-12-19 13:08:09 -08:00
// Also included is the function map provided by the funcmap package
2021-12-19 17:14:00 -08:00
func (c *Controller) parsePageTemplates(page Page) error {
return c.Container.Templates.Parse(
2021-12-19 17:09:01 -08:00
"controller",
2021-12-19 17:14:00 -08:00
page.Name,
page.Layout,
2021-12-19 17:09:01 -08:00
[]string{
2021-12-19 17:14:00 -08:00
fmt.Sprintf("layouts/%s", page.Layout),
fmt.Sprintf("pages/%s", page.Name),
2021-12-19 17:09:01 -08:00
},
[]string{"components"})
2021-12-03 03:11:01 -08:00
}
2021-12-19 07:03:42 -08:00
// executeTemplates executes the cached templates belonging to Page and renders the Page within them
2021-12-19 17:14:00 -08:00
func (c *Controller) executeTemplates(page Page) (*bytes.Buffer, error) {
return c.Container.Templates.Execute("controller", page.Name, page.Layout, page)
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 {
return ctx.Redirect(http.StatusFound, ctx.Echo().Reverse(route, routeParams))
2021-12-03 03:11:01 -08:00
}
2021-12-05 17:22:45 -08:00
2021-12-19 07:03:42 -08:00
// SetValidationErrorMessages sets error flash messages for validation failures of a given struct
// and attempts to provide more user-friendly wording.
// The error should result from the validator module and the data should be the struct that failed
// validation.
// This method supports including a struct tag of "labeL" on each field which will be the name
// of the field used in the error messages, for example:
// - FirstName string `form:"first-name" validate:"required" label:"First name"`
// Only a few validator tags are supported below. Expand them as needed.
2021-12-19 17:14:00 -08:00
func (c *Controller) SetValidationErrorMessages(ctx echo.Context, err error, data interface{}) {
2021-12-19 10:11:23 -08:00
ves, ok := err.(validator.ValidationErrors)
if !ok {
return
}
for _, ve := range ves {
var message string
// Default the field label to the name of the struct field
label := ve.StructField()
// Attempt to get a label from the field's struct tag
if field, ok := reflect.TypeOf(data).FieldByName(ve.Field()); ok {
if labelTag := field.Tag.Get("label"); labelTag != "" {
label = labelTag
}
}
// Provide better error messages depending on the failed validation tag
// This should be expanded as you use additional tags in your validation
switch ve.Tag() {
case "required":
message = "%s is required."
2021-12-14 18:16:48 -08:00
case "email":
message = "%s must be a valid email address."
case "eqfield":
message = "%s must match."
default:
message = "%s is not a valid value."
}
2021-12-19 17:14:00 -08:00
msg.Danger(ctx, fmt.Sprintf(message, "<strong>"+label+"</strong>"))
}
}