preparations for styling: refactor template rendering #1

Merged
Gonne merged 7 commits from styling into main 2022-09-26 10:46:05 +00:00
21 changed files with 175 additions and 82 deletions
Showing only changes of commit f04396809d - Show all commits

View file

@ -7,6 +7,7 @@ import (
"net/mail"
"officeHours/config"
"officeHours/models"
"officeHours/templating"
"strconv"
"strings"
)
@ -149,7 +150,7 @@ func (b *BaseHandler) AddOfficeHourHandler(w http.ResponseWriter, req *http.Requ
id, err := b.officeHourRepo.Add(officeHour)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
b.serveTemplate(w, "addFailure", err)
templating.ServeTemplate(w, "addFailure", err)
return
}
officeHour, err = b.officeHourRepo.FindById(id)
@ -160,7 +161,7 @@ func (b *BaseHandler) AddOfficeHourHandler(w http.ResponseWriter, req *http.Requ
if err != nil {
log.Printf("Error adding request: %s", err.Error())
}
b.serveTemplate(w, "addSuccess", nil)
templating.ServeTemplate(w, "addSuccess", nil)
}
}
@ -172,5 +173,5 @@ func (b *BaseHandler) writeAddOfficeHourMask(w http.ResponseWriter, req *http.Re
if len(data.Errors) != 0 {
w.WriteHeader(http.StatusBadRequest)
}
b.serveTemplate(w, "addMask", data)
templating.ServeTemplate(w, "addMask", data)
}

View file

@ -2,6 +2,7 @@ package controllers
import (
"net/http"
"officeHours/templating"
)
func (b *BaseHandler) ConfirmRequestHandler(w http.ResponseWriter, req *http.Request) {
@ -10,16 +11,16 @@ func (b *BaseHandler) ConfirmRequestHandler(w http.ResponseWriter, req *http.Req
if err != nil {
// TODO: header 404
b.serveTemplate(w, "requestNotFound", nil)
templating.ServeTemplate(w, "requestNotFound", nil)
return
}
err = b.requestRepo.Execute(request)
if err != nil {
// TODO: write header 500
b.serveTemplate(w, "executeFailure", err.Error())
templating.ServeTemplate(w, "executeFailure", err.Error())
return
}
b.serveTemplate(w, "executeSuccess", nil)
templating.ServeTemplate(w, "executeSuccess", nil)
}

View file

@ -4,10 +4,13 @@ package controllers
import (
"net/http"
"officeHours/models"
"officeHours/templating"
"strconv"
)
func (b *BaseHandler) DeleteOfficeHourHandler(w http.ResponseWriter, req *http.Request) {
// TODO: error handling here is by no means sufficient, furthermore
// 400 BadRequest is for technically wrong stuff (most promimently GET instead of POST)
if req.FormValue("id") != "" {
id, err := strconv.Atoi(req.FormValue("id"))
if err != nil {
@ -18,7 +21,7 @@ func (b *BaseHandler) DeleteOfficeHourHandler(w http.ResponseWriter, req *http.R
w.WriteHeader(http.StatusBadRequest)
}
_, err = b.requestRepo.Add(officeHour, models.RequestDelete)
b.serveTemplate(w, "deleteSuccess", nil)
templating.ServeTemplate(w, "deleteSuccess", nil)
} else {
officeHours, _ := b.officeHourRepo.GetAll(true)
timetable, slots := b.GetTimetable(officeHours)

View file

@ -5,6 +5,7 @@ import (
"log"
"net/http"
"officeHours/models"
"officeHours/templating"
"strconv"
)
@ -58,5 +59,5 @@ func (b *BaseHandler) writeTimetablePage(w http.ResponseWriter, req *http.Reques
SelectedRoom int
SelectedCourse int
}{courses, rooms, timetable, selectedRoom, selectedCourse}
b.serveTemplate(w, "index", data)
templating.ServeTemplate(w, "index", data)
}

View file

@ -1,60 +0,0 @@
package controllers
import (
"fmt"
"html/template"
"log"
"net/http"
"officeHours/models"
"os"
)
var funcs = template.FuncMap{
"DayName": models.DayName,
"divide": func(i int, j int) int { return i / j },
}
var baseTemplate = template.Must(template.ParseFiles("templates/base.html")).New("base.html").Funcs(funcs)
// Execute a rendered full HTML page.
//
// If you just want to fill a template snippet, use the RawTemplates object.
//
// Parameters:
// - name is the name of the template file inside templates/, without .html suffix.
// - data is passed through to the template
func (b *BaseHandler) serveTemplate(w http.ResponseWriter, name string, data any) {
full_name := "templates/" + name + ".html"
// check that template exists
info, err := os.Stat(full_name)
if (err != nil && os.IsNotExist(err)) || info.IsDir() {
errMsg := fmt.Sprintf("Template %s nicht gefunden", full_name)
log.Println(errMsg)
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(errMsg))
return
}
tmpl, err := baseTemplate.ParseFiles(full_name)
if err != nil {
errMsg := fmt.Sprintf("Template %s konnte nicht geparst werden : %s", full_name, err.Error())
log.Println(errMsg)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(errMsg))
return
}
// TODO: cache templates in parsed state, but not executed
err = template.Must(tmpl.Clone()).Execute(w, data)
if err != nil {
errMsg := fmt.Sprintf("Template %s konnte nicht ausgeführt werden : %s", full_name, err.Error())
log.Println(errMsg)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(errMsg))
return
}
}
// standalone templates that should not be wrapped into the base.html
var RawTemplates, TemplateError = template.New("").Funcs(funcs).ParseFiles(
"templates/confirmationMail",
"templates/td.html",
"templates/officeHourTable.html")

View file

@ -7,6 +7,7 @@ import (
"html/template"
"log"
"officeHours/models"
"officeHours/templating"
)
func (b *BaseHandler) GetTimetable(officeHours []models.OfficeHour) (timetable map[models.Date]map[int]models.OfficeHour, slots []int) {
@ -85,9 +86,11 @@ func (b *BaseHandler) printTimetable(timetable map[models.Date]map[int]models.Of
MinuteGranularity int
DeleteIcons bool
}{OfficeHour: current, MinuteGranularity: b.config.Date.MinuteGranularity, DeleteIcons: deleteIcons}
templateError := RawTemplates.ExecuteTemplate(&celldata, "td.html", data)
if templateError != nil {
log.Printf("Error executing template td.html: %s", templateError.Error())
err := templating.WriteTemplate(&celldata, "td", data)
if err != nil {
err = fmt.Errorf("writing table cell failed:\n%w", err)
log.Println(err.Error())
// TODO: better error wrapping up to top-level request handler
}
tableBody += celldata.String()
}
@ -120,9 +123,11 @@ func (b *BaseHandler) printTimetable(timetable map[models.Date]map[int]models.Of
slots[4],
template.HTML(tableBody),
}
templateError := RawTemplates.ExecuteTemplate(&table, "officeHourTable.html", tableData)
if templateError != nil {
log.Printf("Error executing template officeHourTable.html: %s", templateError.Error())
err := templating.WriteTemplate(&table, "officeHourTable", tableData)
if err != nil {
err = fmt.Errorf("writing table failed:\n%w", err)
log.Println(err.Error())
// TODO: better error wrapping up to top-level request handler
}
return template.HTML(table.String())
}

15
main.go
View file

@ -11,6 +11,7 @@ import (
"officeHours/controllers"
"officeHours/repositories"
"officeHours/sqldb"
"officeHours/templating"
"os"
)
@ -20,10 +21,6 @@ func main() {
log.SetOutput(logwriter)
}
if controllers.TemplateError != nil {
log.Fatalf("Error parsing templates: %s", controllers.TemplateError.Error())
}
configFile := flag.String(
"config",
"config/config.json",
@ -42,10 +39,16 @@ func main() {
// serve static files
staticHandler := http.FileServer(http.Dir("./static"))
// parse templates
if err = templating.InitTemplates(); err != nil {
log.Print(err.Error())
log.Fatal(">>>\nFatal error occurred, aborting program\n<<<\n")
}
// database connection
db, err := sqldb.Connect(conf)
if err != nil {
log.Fatalf(err.Error())
log.Print(err.Error())
log.Fatal(">>>\nFatal error occurred, aborting program\n<<<\n")
}
// Create repos
roomRepo := repositories.NewRoomRepo(db)

View file

@ -11,8 +11,8 @@ import (
"math/big"
"net/smtp"
"officeHours/config"
"officeHours/controllers"
"officeHours/models"
"officeHours/templating"
)
type RequestRepo struct {
@ -131,12 +131,13 @@ func (r *RequestRepo) sendConfirmationMail(request models.Request) error {
Config config.Config
Request models.Request
}{r.config, request}
err := controllers.RawTemplates.ExecuteTemplate(&message, "confirmationMail", data)
err := templating.WriteTemplate(&message, "confirmationMail", data)
if err != nil {
err = fmt.Errorf("Error parsing confirmation Mail: %w", err)
log.Println(err.Error())
return err
}
switch r.config.Mailer.Type {
case "Stdout":
fmt.Println(message.String())

138
templating/templates.go Normal file
View file

@ -0,0 +1,138 @@
package templating
import (
"fmt"
"html/template"
"io"
"log"
"net/http"
"officeHours/models"
"os"
"time"
)
// parsed templates available for execution
var templates map[string]*template.Template = map[string]*template.Template{}
// Initialise and parse templates.
//
// Should only be called once.
//
// Since this is something which may error and feels like
// it should not be done automatically on import,
// put it into a function.
func InitTemplates() error {
const templateDir = "templating/templates/"
var funcs = template.FuncMap{
"DayName": models.DayName,
"divide": func(i int, j int) int { return i / j },
}
var emptyTemplate = template.New("").Funcs(funcs)
var baseTemplate, err = template.ParseFiles(templateDir + "base.html")
if err != nil {
return fmt.Errorf("parsing base template failed:\n%w", err)
}
baseTemplate.Funcs(funcs)
type toCache struct {
filename string
standalone bool
}
var toParse = map[string]toCache{
// full html templates
"addFailure": {"addFailure.html", false},
"addMask": {"addMask.html", false},
"addSuccess": {"addSuccess.html", false},
"deleteSuccess": {"deleteSuccess.html", false},
"executeFailure": {"executeFailure.html", false},
"executeSuccess": {"executeSuccess.html", false},
"index": {"index.html", false},
"requestNotFound": {"requestNotFound.html", false},
// standalone templates
"confirmationMail": {"confirmationMail", true},
"officeHourTable": {"officeHourTable.html", true},
"td": {"td.html", true},
}
// parse templates and add to global mapping
for key, tmpl := range toParse {
if _, exists := templates[key]; exists {
return fmt.Errorf("template '%s' already parsed", key)
}
fullName := templateDir + tmpl.filename
// check that template file
info, err := os.Stat(fullName)
if err != nil {
return fmt.Errorf("adding template %s failed:\n%w", tmpl.filename, err)
}
if info.IsDir() {
return fmt.Errorf("adding template %s failed: is a directory", tmpl.filename)
}
// parse
var parsed *template.Template
if tmpl.standalone {
parsed, err = emptyTemplate.Clone()
parsed = parsed.New(tmpl.filename)
} else {
parsed, err = baseTemplate.Clone()
}
if err != nil {
return fmt.Errorf("cloning base template failed:\n%w", err)
}
parsed, err = parsed.ParseFiles(fullName)
if err != nil {
return fmt.Errorf("parsing template %s failed:\n%w", tmpl.filename, err)
}
templates[key] = parsed
}
return nil
}
// Execute a template and write it to the given writer.
//
// Parameters:
// - name: name of the template to execute
// - data: passed through to the template
func WriteTemplate(w io.Writer, name string, data any) error {
tmpl, exists := templates[name]
if !exists {
return fmt.Errorf("template %s not available", name)
}
tmpl, err := tmpl.Clone()
if err != nil {
return fmt.Errorf("cloning template failed:\n%w", err)
}
err = tmpl.Execute(w, data)
if err != nil {
return fmt.Errorf("template execution failed:\n%w", err)
}
return nil
}
// Execute a template and write it to a http writer.
//
// Similar to WriteTemplate, but in error case this adds a corresponding
// status code and writes an error message to the writer.
//
// Typically, this is the final action in handling an http request.
//
// Parameters:
// - name: name of the template to execute
// - data: passed through to the template
func ServeTemplate(w http.ResponseWriter, name string, data any) {
// TODO: make this return an error, handle on top of every request handler
err := WriteTemplate(w, name, data)
if err != nil {
err = fmt.Errorf("writing template failed:\n%w", err)
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, `Internal Server Error.
Du kannst uns helfen, indem du folgende Fehlermeldung per Mail
an sprechstunden@mathebau.de sendest:
Fehler um\n
`+time.Now().String()+"\n"+err.Error())
return
}
}