rework template rendering, cache parsed templates
adapt error wrapping principle
This commit is contained in:
parent
7a1448d6f9
commit
f04396809d
21 changed files with 175 additions and 82 deletions
138
templating/templates.go
Normal file
138
templating/templates.go
Normal 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
|
||||
}
|
||||
}
|
7
templating/templates/addFailure.html
Normal file
7
templating/templates/addFailure.html
Normal file
|
@ -0,0 +1,7 @@
|
|||
{{define "title"}}Fehler{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
Irgendetwas ist schief gegangen. Bitte sende folgende Daten an <a href="mailto:sprechstundentool@mathebau.de">sprechstundentool@mathebau.de</a> mit einer Beschreibung, was du tun wolltest.
|
||||
<br />
|
||||
{{.}}
|
||||
{{end}}
|
52
templating/templates/addMask.html
Normal file
52
templating/templates/addMask.html
Normal file
|
@ -0,0 +1,52 @@
|
|||
<{{define "title"}}Sprechstunde anlegen{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
<p>
|
||||
{{range .Errors}}{{.}}<br />{{end}}
|
||||
</p>
|
||||
<form method="POST" action="addOfficeHour">
|
||||
<label for="veranstaltung">Veranstaltung</label>:
|
||||
<select name="veranstaltung" id="veranstaltung">
|
||||
{{range $course := .Courses}}
|
||||
<option value="{{$course.Id}}"{{if eq $course.Id $.SelectedCourse}} selected{{end}}>{{$course.Name}}</option>
|
||||
{{end}}
|
||||
</select><br />
|
||||
<label for="woche">Woche</label>:
|
||||
<select name="woche" id="woche">
|
||||
<option value="0"{{if eq 0 $.Date.Week}} selected{{end}}>Jede</option>
|
||||
<option value="1"{{if eq 1 $.Date.Week}} selected{{end}}>Ungerade</option>
|
||||
<option value="2"{{if eq 2 $.Date.Week}} selected{{end}}>Gerade</option>
|
||||
</select><br />
|
||||
<label for="tag">Tag</label>: <select name="tag" id="tag">
|
||||
<option value="0"{{if eq 0 $.Date.Day}} selected{{end}}>Montag</option>
|
||||
<option value="1"{{if eq 1 $.Date.Day}} selected{{end}}>Dienstag</option>
|
||||
<option value="2"{{if eq 2 $.Date.Day}} selected{{end}}>Mittwoch</option>
|
||||
<option value="3"{{if eq 3 $.Date.Day}} selected{{end}}>Donnerstag</option>
|
||||
<option value="4"{{if eq 4 $.Date.Day}} selected{{end}}>Freitag</option>
|
||||
</select><br />
|
||||
<label for="startzeit">Startzeit</label>: <input type="time" name="startzeit" id="startzeit" min="08:00" max="17:30" {{if gt $.Date.Hour 7}}value="{{printf "%02d" $.Date.Hour}}:{{printf "%02d" $.Date.Minute}}"{{end}} required/><br />
|
||||
<label for="dauer">Dauer in Minuten</label>: <input name="dauer" id="dauer" type="number" min="{{.MinuteGranularity}}" max="120" step="{{.MinuteGranularity}}" value="{{.Duration}}" required/><br />
|
||||
<label for="raum">Raum</label>:
|
||||
<select name="raum" id="raum">
|
||||
{{range $room := .Rooms}}
|
||||
<option value="{{$room.Id}}"{{if eq $room.Id $.SelectedRoom}} selected{{end}}>{{$room.Name}}</option>
|
||||
{{end}}
|
||||
</select><br />
|
||||
<label for="raumname">Raumname (für Sonderräume)</label>: <input type="text" name="raumname" id="raumname" value="{{.Roomname}}"/><br />
|
||||
<label for="name">Name</label>: <input name="name" id="name" type="text" size="50" value="{{.Name}}" required/><br />
|
||||
<label for="email">Email-Adresse</label>:
|
||||
<input name="email" id="email" type="email" size="50" value="{{.Email}}" required/><br />
|
||||
<label for="info">Info</label>: <input name="info" id="info" type="text" size="50" value="{{.Info}}"/><br />
|
||||
<input type="submit">
|
||||
</form>
|
||||
{{if ne .Config.Tutor.MailSuffix ""}}
|
||||
Du musst hier eine Email-Adresse angeben, die auf „{{.Config.Tutor.MailSuffix}}“ endet.<br />
|
||||
{{end}}
|
||||
Außerdem dürfen in Räumen nur begrenzt viele Sprechstunden gleichzeitig stattfinden, nämlich
|
||||
<dl>
|
||||
{{range $room := .Rooms}}
|
||||
<dt>{{$room.Name}}</dt>
|
||||
<dd>{{$room.MaxOccupy}} Sprechstunde{{if gt $room.MaxOccupy 1}}n{{end}}</dd>
|
||||
{{end}}
|
||||
</dl>
|
||||
{{end}}
|
5
templating/templates/addSuccess.html
Normal file
5
templating/templates/addSuccess.html
Normal file
|
@ -0,0 +1,5 @@
|
|||
{{define "title"}}Sprechstunde anlegen{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
Die Sprechstunde wurde angelegt. Du solltest eine Mail mit einem Aktivierungslink erhalten haben.
|
||||
{{end}}
|
27
templating/templates/base.html
Normal file
27
templating/templates/base.html
Normal file
|
@ -0,0 +1,27 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="keywords" content="Mathebau, Sprechstunde, Sprechstunden, Mathe, Mathematik, technische, Universität, Darmstadt, TU, Fachschaft">
|
||||
<meta name="description" content="Eine Übersicht der Sprechstunden, die in den offenen Arbeitsräumen der Fachschaft Mathematik, TU Darmstadt, angeboten werden">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
|
||||
|
||||
<title>{{block "title" .}}Start{{end}} – Sprechstunden</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
{{block "content" .}}Du solltest dies nicht sehen.{{end}}
|
||||
</div>
|
||||
|
||||
<footer class="container">
|
||||
<a href="/">Startseite</a><br />
|
||||
<a href="/addOfficeHour">Sprechstunde anlegen</a><br />
|
||||
<a href="/deleteOfficeHour">Sprechstunde löschen</a><br />
|
||||
Technische Fragen an <a href="mailto:sprechstundentool@mathebau.de">sprechstundentool@mathebau.de</a>
|
||||
</footer>
|
||||
|
||||
<script src="/static/bootstrap/js/bootstrap.bundle.min.js"></script>
|
||||
</body>
|
||||
</html>
|
19
templating/templates/confirmationMail
Normal file
19
templating/templates/confirmationMail
Normal file
|
@ -0,0 +1,19 @@
|
|||
From: {{.Config.Mailer.FromName}}
|
||||
To: {{.Request.OfficeHour.Tutor.Email}}
|
||||
Subject: Sprechstunde {{if eq .Request.Action 1}}anlegen{{end}}{{if eq .Request.Action 2}}löschen{{end}}
|
||||
|
||||
Hallo {{.Request.OfficeHour.Tutor.Name}},
|
||||
|
||||
mit deiner Emailadresse soll eine Sprechstunde mit folgenden Daten {{if eq .Request.Action 1}}angelegt werden{{end}}{{if eq .Request.Action 2}}gelöscht werden{{end}}:
|
||||
|
||||
{{.Request.OfficeHour.Course.Name}}
|
||||
{{DayName .Request.OfficeHour.Date.Day}}
|
||||
{{printf "%02d" .Request.OfficeHour.Date.Hour}}:{{printf "%02d" .Request.OfficeHour.Date.Minute}} Uhr bis {{printf "%02d" .Request.OfficeHour.EndDate.Hour}}:{{printf "%02d" .Request.OfficeHour.EndDate.Minute}} Uhr
|
||||
{{.Request.OfficeHour.Tutor.Name}}
|
||||
{{.Request.OfficeHour.Room.Name}}
|
||||
|
||||
Falls dies richtig ist, so bestätige die Sprechstunde durch Abrufen der folgenden URL:
|
||||
{{.Config.Server.Protocol}}://{{.Config.Server.Domain}}/confirmRequest?code={{.Request.Secret}}
|
||||
Solltest du diese Email nicht erwartet haben, so kannst du sie einfach ignorieren.
|
||||
|
||||
Deine Fachschaft Mathematik
|
7
templating/templates/deleteSuccess.html
Normal file
7
templating/templates/deleteSuccess.html
Normal file
|
@ -0,0 +1,7 @@
|
|||
{{define "title"}}Sprechstunde löschen{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
Du solltest eine Mail mit einem Bestätigungslink erhalten haben. <br />
|
||||
Sie wurde an die Adresse geschickt, mit der die Sprechstunde angelegt wurde.
|
||||
<br />
|
||||
{{end}}
|
7
templating/templates/executeFailure.html
Normal file
7
templating/templates/executeFailure.html
Normal file
|
@ -0,0 +1,7 @@
|
|||
{{define "title"}}Anfrage ausführen fehlgeschlagen{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
Irgendetwas ist schief gegangen. Bitte sende folgende Daten an <a href="mailto:sprechstundentool@mathebau.de">sprechstundentool@mathebau.de</a> mit einer Beschreibung, was du tun wolltest.
|
||||
<br />
|
||||
{{.}}
|
||||
{{end}}
|
5
templating/templates/executeSuccess.html
Normal file
5
templating/templates/executeSuccess.html
Normal file
|
@ -0,0 +1,5 @@
|
|||
{{define "title"}}Anfrage ausgeführt{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
Deine Anfrage wurde ausgeführt.
|
||||
{{end}}
|
25
templating/templates/index.html
Normal file
25
templating/templates/index.html
Normal file
|
@ -0,0 +1,25 @@
|
|||
{{define "title"}}Übersicht{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
<form method="GET" action="/getByCourse">
|
||||
<label for="veranstaltung">Veranstaltung: </label>
|
||||
<select name="veranstaltung" id="veranstaltung" size="1" onchange="document.forms[0].submit()">
|
||||
<option value="">Alle</option>
|
||||
{{range $course := .Courses}}
|
||||
<option value="{{$course.Id}}"{{if eq $course.Id $.SelectedCourse}} selected{{end}}>{{$course.Name}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
<input type="submit" value="Auswählen" />
|
||||
</form>
|
||||
<form method="GET" action="/getByRoom">
|
||||
<label for="raum">Raum: </label>
|
||||
<select name="raum" id="raum" size="1" onchange="document.forms[1].submit()">
|
||||
<option value="">Alle</option>
|
||||
{{range $room := .Rooms}}
|
||||
<option value="{{$room.Id}}"{{if eq $room.Id $.SelectedRoom}} selected{{end}}>{{$room.Name}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
<input type="submit" value="Auswählen" />
|
||||
</form>
|
||||
{{.Timetable}}
|
||||
{{end}}
|
11
templating/templates/officeHourTable.html
Normal file
11
templating/templates/officeHourTable.html
Normal file
|
@ -0,0 +1,11 @@
|
|||
<table>
|
||||
<tr>
|
||||
<th> </th>
|
||||
<th colspan="{{.ColspanMon}}" style="padding-left: 10px; padding-right: 10px; border-right: 1px dotted">Montag</th>
|
||||
<th colspan="{{.ColspanTue}}" style="padding-left: 10px; padding-right: 10px; border-right: 1px dotted">Dienstag</th>
|
||||
<th colspan="{{.ColspanWed}}" style="padding-left: 10px; padding-right: 10px; border-right: 1px dotted">Mittwoch</th>
|
||||
<th colspan="{{.ColspanThu}}" style="padding-left: 10px; padding-right: 10px; border-right: 1px dotted">Donnerstag</th>
|
||||
<th colspan="{{.ColspanFri}}" style="padding-left: 10px; padding-right: 10px; border-right: 1px dotted">Freitag</th>
|
||||
</tr>
|
||||
{{.TableBody}}
|
||||
</table>
|
12
templating/templates/requestNotFound.html
Normal file
12
templating/templates/requestNotFound.html
Normal file
|
@ -0,0 +1,12 @@
|
|||
{{define "title"}}Anfrage bestätigen fehlgeschlagen{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
<p>
|
||||
Dieser Bestätigungscode ist nicht verfügbar. <br />
|
||||
Bitte gib deinen Bestätigungscode hier ein.
|
||||
</p>
|
||||
<form action="/confirmRequest">
|
||||
<label for="code">Bestätigungscode</label>: <input type="text" name="code" id="code"/>
|
||||
<input type="submit" />
|
||||
</form>
|
||||
{{end}}
|
9
templating/templates/td.html
Normal file
9
templating/templates/td.html
Normal file
|
@ -0,0 +1,9 @@
|
|||
<td rowspan="{{divide .OfficeHour.Duration .MinuteGranularity}}" style="border: 1px solid">
|
||||
{{if .DeleteIcons}}<div style="text-align: right;"><a href="/deleteOfficeHour?id={{.OfficeHour.Id}}">❌</a></div>{{end}}
|
||||
{{printf "%02d" .OfficeHour.Date.Hour}}:{{printf "%02d" .OfficeHour.Date.Minute}} - {{printf "%02d" .OfficeHour.EndDate.Hour}}:{{printf "%02d" .OfficeHour.EndDate.Minute}}<br />
|
||||
{{if eq .OfficeHour.Date.Week 1}}in ungeraden Wochen<br />{{end}}{{if eq .OfficeHour.Date.Week 2}}in geraden Wochen<br />{{end}}
|
||||
{{.OfficeHour.Course.Name}}<br />
|
||||
{{.OfficeHour.Tutor.Name}}<br />
|
||||
{{.OfficeHour.Room.Name}}<br />
|
||||
{{if ne .OfficeHour.Info ""}}{{.OfficeHour.Info}}<br />{{end}}
|
||||
</td>
|
Loading…
Add table
Add a link
Reference in a new issue