views.go
220 lines1
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package application
import (
"fmt"
"html/template"
"io/fs"
"log"
"maps"
"net/http"
"os"
"path/filepath"
"strings"
)
// View is an http.Handler that renders a template
type View struct {
*App
template string
bouncer Bouncer
}
// ServeHTTP implements http.Handler
func (v *View) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if v.bouncer != nil && !v.bouncer(v.App, w, r) {
return
}
v.App.render(w, r, v.template, nil)
}
// Render renders a template with optional data
func (c *BaseController) Render(w http.ResponseWriter, r *http.Request, templateName string, data any) {
c.App.render(w, r, templateName, data)
}
// render executes a template with controllers injected as template functions
func (app *App) render(w http.ResponseWriter, r *http.Request, name string, data any) {
tmpl, err := app.loadView(name)
if err != nil {
log.Printf("Template load error: %v", err)
http.Error(w, "Template error", http.StatusInternalServerError)
return
}
// Inject controllers as template functions (accessible as {{home.Method}})
funcs := template.FuncMap{}
for ctrlName, ctrl := range app.controllers {
funcs[ctrlName] = func() Controller {
return ctrl.Handle(r)
}
}
// Per-request nonce for CSP
nonce := NonceFromContext(r.Context())
funcs["nonce"] = func() string { return nonce }
if app.ScriptFunc != nil {
funcs["frontend_script"] = func() template.HTML { return app.ScriptFunc(nonce) }
}
// Buffer template execution to prevent partial writes on error
var buf strings.Builder
if err := tmpl.Funcs(funcs).ExecuteTemplate(&buf, name, data); err != nil {
log.Printf("Template error: %v", err)
http.Error(w, "Template error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(buf.String()))
}
// RenderError renders an error message (returns 200 for HTMX compatibility).
// In production (ENV=production), internal error details are hidden to prevent
// information leakage. Full errors are logged for debugging.
func RenderError(w http.ResponseWriter, r *http.Request, err error) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
message := err.Error()
// In production, hide all internal error details
if os.Getenv("ENV") == "production" {
log.Printf("[error] %s %s: %v", r.Method, r.URL.Path, err)
message = "An error occurred. Please try again."
}
fmt.Fprintf(w, `<div class="alert alert-error">%s</div>`, template.HTMLEscapeString(message))
}
// RenderError delegates to the standalone RenderError function.
// Kept for backward compatibility with existing controllers.
func (c *BaseController) RenderError(w http.ResponseWriter, r *http.Request, err error) {
RenderError(w, r, err)
}
// RenderToString renders a template to a string.
// For partials (already in base templates), use just the filename: "live-time.html"
// For views, use the path relative to views/: "index.html" or "admin/dashboard.html"
func (app *App) RenderToString(name string, data any) (string, error) {
// Clone base templates (required - executing marks templates as used)
tmpl, err := app.base.Clone()
if err != nil {
return "", err
}
var buf strings.Builder
// Check if template exists in base (partials, layouts)
if t := tmpl.Lookup(name); t != nil {
if err := t.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
// Otherwise load as a view file
path := "views/" + name
content, err := fs.ReadFile(app.viewsFS, path)
if err != nil {
return "", fmt.Errorf("template not found: %s", name)
}
if _, err := tmpl.New(name).Parse(string(content)); err != nil {
return "", err
}
if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
return "", err
}
return buf.String(), nil
}
// parseBaseTemplates parses only layouts and partials from the filesystem.
// These are loaded once at startup and cloned for each request.
func (app *App) parseBaseTemplates(views fs.FS) *template.Template {
funcs := app.templateFuncs()
// Register placeholder functions for controllers (replaced per-request in render)
for name := range app.controllers {
funcs[name] = func() Controller { return nil }
}
// Placeholder funcs (replaced per-request in render)
funcs["nonce"] = func() string { return "" }
funcs["frontend_script"] = func() template.HTML { return "" }
tmpl := template.New("").Funcs(funcs)
// Only load from layouts/ and partials/ directories
for _, dir := range []string{"views/layouts", "views/partials"} {
if err := fs.WalkDir(views, dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(path, ".html") {
return nil
}
content, err := fs.ReadFile(views, path)
if err != nil {
return fmt.Errorf("read %s: %w", path, err)
}
name := filepath.Base(path)
if _, err := tmpl.New(name).Parse(string(content)); err != nil {
log.Printf("Failed to parse template %s: %v", name, err)
}
return nil
}); err != nil {
log.Printf("Warning: could not load templates from %s: %v", dir, err)
}
}
return tmpl
}
// loadView loads a view file on-demand, cloning base templates (layouts + partials)
// and parsing the specific view file into the clone.
func (app *App) loadView(name string) (*template.Template, error) {
// Clone base templates (layouts + partials)
tmpl, err := app.base.Clone()
if err != nil {
return nil, err
}
// Try to load the view file
path := "views/" + name
content, err := fs.ReadFile(app.viewsFS, path)
if err != nil {
return nil, fmt.Errorf("view not found: %s", name)
}
// Parse view into cloned template
_, err = tmpl.New(name).Parse(string(content))
return tmpl, err
}
// templateFuncs returns the custom template functions available to all views and emails
func (app *App) templateFuncs() template.FuncMap {
funcs := template.FuncMap{
"dict": func(values ...any) map[string]any {
if len(values)%2 != 0 {
return nil
}
m := make(map[string]any, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
continue
}
m[key] = values[i+1]
}
return m
},
}
// Merge user-defined funcs (globally available in views and emails)
maps.Copy(funcs, app.funcs)
return funcs
}