saasitone/controllers/router.go

76 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"
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("/", StaticDir)
2021-12-03 03:11:01 -08:00
// Middleware
2021-12-03 05:18:40 -08:00
c.Web.Use(echomw.RemoveTrailingSlashWithConfig(echomw.TrailingSlashConfig{
2021-12-03 03:11:01 -08:00
RedirectCode: http.StatusMovedPermanently,
}))
2021-12-03 05:18:40 -08:00
c.Web.Use(echomw.RequestID())
c.Web.Use(echomw.Recover())
c.Web.Use(echomw.Gzip())
c.Web.Use(echomw.Logger())
2021-12-07 18:36:57 -08:00
c.Web.Use(echomw.TimeoutWithConfig(echomw.TimeoutConfig{
Timeout: c.Config.App.Timeout,
}))
c.Web.Use(middleware.PageCache(c.Cache))
2021-12-03 03:11:01 -08:00
c.Web.Use(session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))))
2021-12-03 05:18:40 -08:00
c.Web.Use(echomw.CSRFWithConfig(echomw.CSRFConfig{
2021-12-03 04:53:01 -08:00
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(c.Web, ctr)
userRoutes(c.Web, ctr)
}
2021-12-05 17:22:45 -08:00
func navRoutes(e *echo.Echo, ctr Controller) {
home := Home{Controller: ctr}
2021-12-03 03:11:01 -08:00
e.GET("/", home.Get).Name = "home"
2021-12-05 17:22:45 -08:00
about := About{Controller: ctr}
2021-12-03 03:11:01 -08:00
e.GET("/about", about.Get).Name = "about"
2021-12-05 17:22:45 -08:00
contact := Contact{Controller: ctr}
2021-12-03 03:11:01 -08:00
e.GET("/contact", contact.Get).Name = "contact"
e.POST("/contact", contact.Post).Name = "contact.post"
}
2021-12-05 17:22:45 -08:00
func userRoutes(e *echo.Echo, ctr Controller) {
login := Login{Controller: ctr}
2021-12-03 12:41:40 -08:00
e.GET("/user/login", login.Get).Name = "login"
2021-12-03 13:35:11 -08:00
e.POST("/user/login", login.Post).Name = "login.post"
2021-12-05 17:22:45 -08:00
register := Register{Controller: ctr}
2021-12-03 13:35:11 -08:00
e.GET("/user/register", register.Get).Name = "register"
e.POST("/user/register", register.Post).Name = "register.post"
2021-12-03 03:11:01 -08:00
}