-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
80 lines (68 loc) · 2 KB
/
render.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"fmt"
"html/template"
"net/http"
"subscription-service/data"
"time"
)
var pathToTemplates = "./templates"
type TemplateData struct {
StringMap map[string]string
IntMap map[string]int
FloatMap map[string]float64
Data map[string]any
Flash string
Warning string
Error string
Authenticated bool
Now time.Time
User *data.User
}
func (app *Config) render(w http.ResponseWriter, r *http.Request, t string, td *TemplateData) {
partials := []string{
fmt.Sprintf("%s/base.layout.gohtml", pathToTemplates),
fmt.Sprintf("%s/header.partial.gohtml", pathToTemplates),
fmt.Sprintf("%s/navbar.partial.gohtml", pathToTemplates),
fmt.Sprintf("%s/footer.partial.gohtml", pathToTemplates),
fmt.Sprintf("%s/alerts.partial.gohtml", pathToTemplates),
}
var templateSlice []string
templateSlice = append(templateSlice, fmt.Sprintf("%s/%s", pathToTemplates, t))
for _, x := range partials {
templateSlice = append(templateSlice, x)
}
if td == nil {
td = &TemplateData{}
}
tmpl, err := template.ParseFiles(templateSlice...)
if err != nil {
app.ErrorLog.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, app.AddDefaultData(td, r)); err != nil {
app.ErrorLog.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (app *Config) AddDefaultData(td *TemplateData, r *http.Request) *TemplateData {
td.Flash = app.Session.PopString(r.Context(), "flash")
td.Warning = app.Session.PopString(r.Context(), "warning")
td.Error = app.Session.PopString(r.Context(), "error")
if app.IsAuthenticated(r) {
td.Authenticated = true
user, ok := app.Session.Get(r.Context(), "user").(data.User)
if !ok {
app.ErrorLog.Println("cant get user from session")
} else {
td.User = &user
}
}
td.Now = time.Now()
return td
}
func (app *Config) IsAuthenticated(r *http.Request) bool {
return app.Session.Exists(r.Context(), "userID")
}