Creating handlers for forms & adding CSRF Protection

This commit is contained in:
Muyao CHEN
2024-06-30 10:31:15 +02:00
parent 592d5241d1
commit 76bee566cd
6 changed files with 28 additions and 15 deletions

View File

@ -8,6 +8,8 @@ import (
"log"
"net/http"
"path/filepath"
"github.com/justinas/nosurf"
)
var app *config.AppConfig
@ -18,12 +20,13 @@ func NewTemplates(a *config.AppConfig) {
}
// AddDefaultData adds default template data
func AddDefaultData(td *models.TemplateData) *models.TemplateData {
func AddDefaultData(td *models.TemplateData, r *http.Request) *models.TemplateData {
td.CSRFToken = nosurf.Token(r)
return td
}
// RenderTemplate renders a HTML template file
func RenderTemplate(w http.ResponseWriter, tmpl string, td *models.TemplateData) {
func RenderTemplate(w http.ResponseWriter, r *http.Request, tmpl string, td *models.TemplateData) {
var tc map[string]*template.Template
if app.UseCache {
// get the template cache from the app config
@ -42,7 +45,7 @@ func RenderTemplate(w http.ResponseWriter, tmpl string, td *models.TemplateData)
// written successfully
buf := new(bytes.Buffer)
td = AddDefaultData(td)
td = AddDefaultData(td, r)
err := t.Execute(buf, td)
if err != nil {