Added timeout middleware and config.

This commit is contained in:
mikestefanello 2021-12-06 21:51:21 -05:00
parent 3a45695083
commit 855d67409f
4 changed files with 13 additions and 10 deletions

View File

@ -34,9 +34,10 @@ type HTTPConfig struct {
// AppConfig stores application configuration
type AppConfig struct {
Name string `env:"APP_NAME,default=Goweb"`
Environment Env `env:"APP_ENV,default=local"`
EncryptionKey string `env:"APP_ENCRYPTION_KEY,default=?E(G+KbPeShVmYq3t6w9z$C&F)J@McQf"`
Name string `env:"APP_NAME,default=Goweb"`
Environment Env `env:"APP_ENV,default=local"`
EncryptionKey string `env:"APP_ENCRYPTION_KEY,default=?E(G+KbPeShVmYq3t6w9z$C&F)J@McQf"`
Timeout time.Duration `env:"APP_TIMEOUT,default=20s"`
}
type CacheConfig struct {
@ -45,7 +46,7 @@ type CacheConfig struct {
Password string `env:"CACHE_PASSWORD"`
MaxAge struct {
StaticFile time.Duration `env:"CACHE_MAX_AGE_STATIC_FILE,default=4380h"`
Page time.Duration `env:"CACHE_STATIC_FILE_MAX_AGE,default=24h"`
Page time.Duration `env:"CACHE_MAX_PAGE_PAGE,default=24h"`
}
}

View File

@ -2,7 +2,6 @@ package controllers
import (
"bytes"
"context"
"fmt"
"html/template"
"net/http"
@ -45,6 +44,8 @@ func NewController(c *container.Container) Controller {
}
}
// TODO: Audit error handling (ie NewHTTPError)
func (t *Controller) RenderPage(c echo.Context, p Page) error {
if p.Name == "" {
c.Logger().Error("Page render failed due to missing name")
@ -78,13 +79,12 @@ func (t *Controller) cachePage(c echo.Context, p Page) {
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)
err := t.Container.Cache.Set(c.Request().Context(), key, "my-value", opts)
if err != nil {
c.Logger().Errorf("Failed to cache page: %s", key)
c.Logger().Error(err)

View File

@ -8,7 +8,7 @@ import (
"goweb/msg"
"goweb/pager"
"github.com/labstack/echo/v4/middleware"
echomw "github.com/labstack/echo/v4/middleware"
"github.com/labstack/echo/v4"
)
@ -53,7 +53,7 @@ func NewPage(c echo.Context) Page {
p.IsHome = p.Path == "/"
if csrf := c.Get(middleware.DefaultCSRFConfig.ContextKey); csrf != nil {
if csrf := c.Get(echomw.DefaultCSRFConfig.ContextKey); csrf != nil {
p.CSRF = csrf.(string)
}

View File

@ -28,7 +28,9 @@ func BuildRouter(c *container.Container) {
c.Web.Use(echomw.CSRFWithConfig(echomw.CSRFConfig{
TokenLookup: "form:csrf",
}))
c.Web.Use(echomw.TimeoutWithConfig(echomw.TimeoutConfig{
Timeout: c.Config.App.Timeout,
}))
// Static files with proper cache control
// funcmap.File() should be used in templates to append a cache key to the URL in order to break cache
// after each server restart