Refactoring for Gin, NoSurf and SCS continues.
This commit is contained in:
63
internal/handlers/template/error.go
Normal file
63
internal/handlers/template/error.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package handlers
|
||||
|
||||
// ToDo not nessisarily an issue with this file but ✅ internal/handlers/template/
|
||||
//→ For anything that handles HTTP rendering (RenderError, RenderPage)
|
||||
|
||||
//✅ internal/helpers/template/
|
||||
//→ For anything that helps render (TemplateContext, pagination, funcs)
|
||||
// there for bear usages between helpers and handlers
|
||||
//In clean Go architecture (especially following “Package by responsibility”):
|
||||
|
||||
//Type Responsibility Should access
|
||||
//Helpers / Utilities Pure, stateless logic — e.g. template functions, math, formatters. Shared logic, no config, no HTTP handlers.
|
||||
//Handlers Own an HTTP concern — e.g. routes, rendering responses, returning templates or JSON. Injected dependencies (cfg, db, etc.). Should use helpers, not vice versa.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
templateHelpers "synlotto-website/internal/helpers/template"
|
||||
|
||||
"synlotto-website/internal/models"
|
||||
)
|
||||
|
||||
func RenderError(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
statusCode int,
|
||||
siteName string,
|
||||
copyrightYearStart int,
|
||||
) {
|
||||
log.Printf("⚙️ RenderError called with status: %d", statusCode)
|
||||
|
||||
context := templateHelpers.TemplateContext(
|
||||
w, r,
|
||||
models.TemplateData{},
|
||||
siteName,
|
||||
copyrightYearStart,
|
||||
)
|
||||
|
||||
pagePath := fmt.Sprintf("templates/error/%d.html", statusCode)
|
||||
log.Printf("📄 Checking for template file: %s", pagePath)
|
||||
|
||||
if _, err := os.Stat(pagePath); err != nil {
|
||||
log.Printf("🚫 Template file missing: %s", err)
|
||||
http.Error(w, http.StatusText(statusCode), statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("✅ Template file found, loading...")
|
||||
|
||||
tmpl := templateHelpers.LoadTemplateFiles(fmt.Sprintf("%d.html", statusCode), pagePath)
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
|
||||
log.Printf("❌ Failed to render error page layout: %v", err)
|
||||
http.Error(w, http.StatusText(statusCode), statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("✅ Successfully rendered error page") // ToDo: log these to db
|
||||
}
|
||||
Reference in New Issue
Block a user