Stack of changes to get gin, scs, nosurf running.
This commit is contained in:
55
internal/http/error/errors.go
Normal file
55
internal/http/error/errors.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
templateHelpers "synlotto-website/internal/helpers/template"
|
||||
"synlotto-website/internal/models"
|
||||
|
||||
"github.com/alexedwards/scs/v2"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RenderStatus renders web/templates/error/<status>.html inside layout.html.
|
||||
func RenderStatus(c *gin.Context, sessions *scs.SessionManager, status int) {
|
||||
// Base context
|
||||
ctx := templateHelpers.TemplateContext(c.Writer, c.Request, models.TemplateData{})
|
||||
|
||||
// Flash (SCS)
|
||||
if f := sessions.PopString(c.Request.Context(), "flash"); f != "" {
|
||||
ctx["Flash"] = f
|
||||
}
|
||||
|
||||
// Use your finalized paths
|
||||
pagePath := fmt.Sprintf("web/templates/error/%d.html", status)
|
||||
if _, err := os.Stat(pagePath); err != nil {
|
||||
c.String(status, http.StatusText(status))
|
||||
return
|
||||
}
|
||||
|
||||
// Keep your "layout first" load order
|
||||
tmpl := templateHelpers.LoadTemplateFiles(
|
||||
"web/templates/layout.html",
|
||||
pagePath,
|
||||
)
|
||||
|
||||
c.Status(status)
|
||||
if err := tmpl.ExecuteTemplate(c.Writer, "layout", ctx); err != nil {
|
||||
c.String(status, http.StatusText(status))
|
||||
}
|
||||
}
|
||||
|
||||
// Adapters so bootstrap can wire these without lambdas everywhere.
|
||||
func NoRoute(sessions *scs.SessionManager) gin.HandlerFunc {
|
||||
return func(c *gin.Context) { RenderStatus(c, sessions, http.StatusNotFound) }
|
||||
}
|
||||
func NoMethod(sessions *scs.SessionManager) gin.HandlerFunc {
|
||||
return func(c *gin.Context) { RenderStatus(c, sessions, http.StatusMethodNotAllowed) }
|
||||
}
|
||||
func Recovery(sessions *scs.SessionManager) gin.RecoveryFunc {
|
||||
return func(c *gin.Context, _ interface{}) {
|
||||
RenderStatus(c, sessions, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user