saasitone/controllers/router.go

83 lines
2.0 KiB
Go
Raw Normal View History

2021-12-05 17:22:45 -08:00
package controllers
2021-12-03 03:11:01 -08:00
import (
"net/http"
2021-12-03 05:18:40 -08:00
"goweb/middleware"
2021-12-03 03:11:01 -08:00
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
2021-12-07 18:36:57 -08:00
2021-12-03 03:11:01 -08:00
"github.com/labstack/echo/v4"
2021-12-03 05:18:40 -08:00
echomw "github.com/labstack/echo/v4/middleware"
2021-12-03 03:11:01 -08:00
"goweb/container"
)
const (
StaticDir = "static"
StaticPrefix = "files"
)
2021-12-03 03:11:01 -08:00
func BuildRouter(c *container.Container) {
2021-12-07 18:36:57 -08:00
// 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
c.Web.Group("", middleware.CacheControl(c.Config.Cache.MaxAge.StaticFile)).
Static(StaticPrefix, StaticDir)
2021-12-07 18:36:57 -08:00
2021-12-03 03:11:01 -08:00
// Middleware
g := c.Web.Group("",
echomw.RemoveTrailingSlashWithConfig(echomw.TrailingSlashConfig{
RedirectCode: http.StatusMovedPermanently,
}),
echomw.Recover(),
2021-12-08 19:21:07 -08:00
echomw.Secure(),
echomw.RequestID(),
echomw.Gzip(),
echomw.Logger(),
middleware.LogRequestID(),
echomw.TimeoutWithConfig(echomw.TimeoutConfig{
Timeout: c.Config.App.Timeout,
}),
middleware.PageCache(c.Cache),
session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))),
echomw.CSRFWithConfig(echomw.CSRFConfig{
TokenLookup: "form:csrf",
}),
)
2021-12-03 05:06:06 -08:00
2021-12-03 03:11:01 -08:00
// Base controller
2021-12-05 17:22:45 -08:00
ctr := NewController(c)
2021-12-03 03:11:01 -08:00
// Error handler
2021-12-05 17:22:45 -08:00
err := Error{Controller: ctr}
2021-12-03 03:11:01 -08:00
c.Web.HTTPErrorHandler = err.Get
// Routes
navRoutes(g, ctr)
userRoutes(g, ctr)
2021-12-03 03:11:01 -08:00
}
func navRoutes(g *echo.Group, ctr Controller) {
2021-12-05 17:22:45 -08:00
home := Home{Controller: ctr}
g.GET("/", home.Get).Name = "home"
2021-12-03 03:11:01 -08:00
2021-12-05 17:22:45 -08:00
about := About{Controller: ctr}
g.GET("/about", about.Get).Name = "about"
2021-12-03 03:11:01 -08:00
2021-12-05 17:22:45 -08:00
contact := Contact{Controller: ctr}
g.GET("/contact", contact.Get).Name = "contact"
g.POST("/contact", contact.Post).Name = "contact.post"
2021-12-03 03:11:01 -08:00
}
func userRoutes(g *echo.Group, ctr Controller) {
2021-12-05 17:22:45 -08:00
login := Login{Controller: ctr}
g.GET("/user/login", login.Get).Name = "login"
g.POST("/user/login", login.Post).Name = "login.post"
2021-12-03 13:35:11 -08:00
2021-12-05 17:22:45 -08:00
register := Register{Controller: ctr}
g.GET("/user/register", register.Get).Name = "register"
g.POST("/user/register", register.Post).Name = "register.post"
2021-12-03 03:11:01 -08:00
}