2021-12-12 19:09:13 -08:00
|
|
|
package controller
|
2021-12-03 03:11:01 -08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2021-12-19 07:03:42 -08:00
|
|
|
"errors"
|
2021-12-03 03:11:01 -08:00
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
2021-12-05 17:22:45 -08:00
|
|
|
"path"
|
|
|
|
"path/filepath"
|
2021-12-14 17:54:47 -08:00
|
|
|
"reflect"
|
2021-12-05 17:22:45 -08:00
|
|
|
"runtime"
|
2021-12-03 03:11:01 -08:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"goweb/config"
|
|
|
|
"goweb/funcmap"
|
2021-12-07 18:36:57 -08:00
|
|
|
"goweb/middleware"
|
2021-12-14 17:54:47 -08:00
|
|
|
"goweb/msg"
|
2021-12-18 07:07:12 -08:00
|
|
|
"goweb/services"
|
2021-12-14 17:54:47 -08:00
|
|
|
|
|
|
|
"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"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2021-12-18 13:55:35 -08:00
|
|
|
// templates stores a cache of parsed page templates
|
2021-12-03 03:11:01 -08:00
|
|
|
templates = sync.Map{}
|
|
|
|
|
2021-12-18 13:55:35 -08:00
|
|
|
// funcMap stores the Template function map
|
2021-12-03 03:11:01 -08:00
|
|
|
funcMap = funcmap.GetFuncMap()
|
2021-12-05 17:22:45 -08:00
|
|
|
|
2021-12-18 13:55:35 -08:00
|
|
|
// templatePath stores the complete path to the templates directory
|
2021-12-05 17:22:45 -08:00
|
|
|
templatePath = getTemplatesDirectoryPath()
|
2021-12-03 03:11:01 -08:00
|
|
|
)
|
|
|
|
|
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-03 03:11:01 -08:00
|
|
|
func (t *Controller) RenderPage(c echo.Context, p Page) error {
|
2021-12-19 07:03:42 -08:00
|
|
|
// Page name is required
|
2021-12-03 03:11:01 -08:00
|
|
|
if p.Name == "" {
|
2021-12-07 18:36:57 -08:00
|
|
|
c.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-03 03:11:01 -08:00
|
|
|
if p.AppName == "" {
|
|
|
|
p.AppName = t.Container.Config.App.Name
|
|
|
|
}
|
|
|
|
|
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-03 03:11:01 -08:00
|
|
|
if err := t.parsePageTemplates(p); err != nil {
|
2021-12-19 07:03:42 -08:00
|
|
|
c.Logger().Errorf("failed to parse templates: %v", err)
|
|
|
|
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-06 11:53:28 -08:00
|
|
|
buf, err := t.executeTemplates(c, p)
|
2021-12-03 03:11:01 -08:00
|
|
|
if err != nil {
|
2021-12-19 07:03:42 -08:00
|
|
|
c.Logger().Errorf("failed to execute templates: %v", err)
|
|
|
|
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-07 18:36:57 -08:00
|
|
|
t.cachePage(c, p, buf)
|
|
|
|
|
|
|
|
// Set any headers
|
|
|
|
for k, v := range p.Headers {
|
|
|
|
c.Response().Header().Set(k, v)
|
|
|
|
}
|
2021-12-06 11:53:28 -08:00
|
|
|
|
2021-12-03 03:11:01 -08:00
|
|
|
return c.HTMLBlob(p.StatusCode, buf.Bytes())
|
|
|
|
}
|
|
|
|
|
2021-12-19 07:03:42 -08:00
|
|
|
// cachePage caches the HTML for a given Page if the Page has caching enabled
|
2021-12-07 18:36:57 -08:00
|
|
|
func (t *Controller) cachePage(c echo.Context, p Page, html *bytes.Buffer) {
|
2021-12-06 11:53:28 -08:00
|
|
|
if !p.Cache.Enabled {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-12-19 07:03:42 -08:00
|
|
|
// If no expiration time was provided, default to the configuration value
|
2021-12-11 16:32:34 -08:00
|
|
|
if p.Cache.Expiration == 0 {
|
|
|
|
p.Cache.Expiration = t.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-06 11:53:28 -08:00
|
|
|
key := c.Request().URL.String()
|
|
|
|
opts := &store.Options{
|
2021-12-11 16:32:34 -08:00
|
|
|
Expiration: p.Cache.Expiration,
|
2021-12-06 11:53:28 -08:00
|
|
|
Tags: p.Cache.Tags,
|
|
|
|
}
|
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: p.Headers,
|
|
|
|
StatusCode: p.StatusCode,
|
|
|
|
}
|
2021-12-19 07:03:42 -08:00
|
|
|
|
2021-12-07 18:36:57 -08:00
|
|
|
err := marshaler.New(t.Container.Cache).Set(c.Request().Context(), key, cp, opts)
|
2021-12-06 11:53:28 -08:00
|
|
|
if err != nil {
|
2021-12-08 18:55:30 -08:00
|
|
|
c.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-08 18:55:30 -08:00
|
|
|
c.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-03 03:11:01 -08:00
|
|
|
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
|
|
|
|
if _, ok := templates.Load(p.Name); !ok || t.Container.Config.App.Environment == config.EnvLocal {
|
2021-12-19 07:03:42 -08:00
|
|
|
// Parse the Layout and Name templates
|
2021-12-03 03:11:01 -08:00
|
|
|
parsed, err :=
|
2021-12-10 05:33:49 -08:00
|
|
|
template.New(p.Layout+config.TemplateExt).
|
2021-12-03 03:11:01 -08:00
|
|
|
Funcs(funcMap).
|
|
|
|
ParseFiles(
|
2021-12-10 05:33:49 -08:00
|
|
|
fmt.Sprintf("%s/layouts/%s%s", templatePath, p.Layout, config.TemplateExt),
|
|
|
|
fmt.Sprintf("%s/pages/%s%s", templatePath, p.Name, config.TemplateExt),
|
2021-12-03 03:11:01 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-19 07:03:42 -08:00
|
|
|
// Parse all templates within the components directory
|
2021-12-10 05:33:49 -08:00
|
|
|
parsed, err = parsed.ParseGlob(fmt.Sprintf("%s/components/*%s", templatePath, config.TemplateExt))
|
2021-12-03 03:11:01 -08:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store the template so this process only happens once
|
|
|
|
templates.Store(p.Name, parsed)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-12-19 07:03:42 -08:00
|
|
|
// executeTemplates executes the cached templates belonging to Page and renders the Page within them
|
2021-12-06 11:53:28 -08:00
|
|
|
func (t *Controller) executeTemplates(c echo.Context, p Page) (*bytes.Buffer, error) {
|
|
|
|
tmpl, ok := templates.Load(p.Name)
|
|
|
|
if !ok {
|
2021-12-19 07:03:42 -08:00
|
|
|
return nil, errors.New("uncached page template requested")
|
2021-12-06 11:53:28 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
buf := new(bytes.Buffer)
|
2021-12-10 05:33:49 -08:00
|
|
|
err := tmpl.(*template.Template).ExecuteTemplate(buf, p.Layout+config.TemplateExt, p)
|
2021-12-06 11:53:28 -08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf, nil
|
|
|
|
}
|
|
|
|
|
2021-12-19 07:03:42 -08:00
|
|
|
// Redirect redirects to a given route name with optional route parameters
|
2021-12-03 03:11:01 -08:00
|
|
|
func (t *Controller) Redirect(c echo.Context, route string, routeParams ...interface{}) error {
|
|
|
|
return c.Redirect(http.StatusFound, c.Echo().Reverse(route, routeParams))
|
|
|
|
}
|
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-14 17:54:47 -08:00
|
|
|
func (t *Controller) SetValidationErrorMessages(c echo.Context, err error, data interface{}) {
|
|
|
|
for _, ve := range err.(validator.ValidationErrors) {
|
|
|
|
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
|
2021-12-18 13:55:35 -08:00
|
|
|
// This should be expanded as you use additional tags in your validation
|
2021-12-14 17:54:47 -08:00
|
|
|
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."
|
2021-12-14 17:54:47 -08:00
|
|
|
default:
|
|
|
|
message = "%s is not a valid value."
|
|
|
|
}
|
|
|
|
|
2021-12-14 18:16:48 -08:00
|
|
|
msg.Danger(c, fmt.Sprintf(message, "<strong>"+label+"</strong>"))
|
2021-12-14 17:54:47 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-05 17:22:45 -08:00
|
|
|
// getTemplatesDirectoryPath gets the templates directory path
|
|
|
|
// This is needed incase this is called from a package outside of main,
|
2021-12-18 13:55:35 -08:00
|
|
|
// such as within tests
|
2021-12-05 17:22:45 -08:00
|
|
|
func getTemplatesDirectoryPath() string {
|
|
|
|
_, b, _, _ := runtime.Caller(0)
|
|
|
|
d := path.Join(path.Dir(b))
|
2021-12-10 05:33:49 -08:00
|
|
|
return filepath.Join(filepath.Dir(d), config.TemplateDir)
|
2021-12-05 17:22:45 -08:00
|
|
|
}
|