/
templates.go
334 lines (299 loc) · 9.45 KB
/
templates.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright (c) 2017, Janoš Guljaš <janos@resenje.org>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package templates
import (
"bytes"
"fmt"
"html/template"
"log/slog"
"net/http"
"os"
"path/filepath"
)
// Error is a common error type that holds
// information about error message and template name.
type Error struct {
Err error
Template string
}
func (e *Error) Error() string {
if e.Template == "" {
return e.Err.Error()
}
return fmt.Sprintf("%s: %s", e.Err.Error(), e.Template)
}
// FileReadFunc returns the content of file referenced
// by filename. It hes the same signature as os.ReadFile
// function.
type FileReadFunc func(filename string) ([]byte, error)
// ErrUnknownTemplate will be returned by Render function if
// the template does not exist.
var ErrUnknownTemplate = fmt.Errorf("unknown template")
// Options holds parameters for creating Templates.
type Options struct {
fileFindFunc func(filename string) string
fileReadFunc FileReadFunc
fileReadOnRender bool
contentType string
files map[string][]string
strings map[string][]string
functions template.FuncMap
delimOpen string
delimClose string
logger *slog.Logger
}
// Option sets parameters used in New function.
type Option func(*Options)
// WithContentType sets the content type HTTP header that
// will be written on Render and Response functions.
func WithContentType(contentType string) Option {
return func(o *Options) { o.contentType = contentType }
}
// WithBaseDir sets the directory in which template files
// are stored.
func WithBaseDir(dir string) Option {
return func(o *Options) {
o.fileFindFunc = func(f string) string {
return filepath.Join(dir, f)
}
}
}
// WithFileFindFunc sets the function that will return the
// file path on disk based on filename provided from files
// defind using WithTemplateFromFile or WithTemplateFromFiles.
func WithFileFindFunc(fn func(filename string) string) Option {
return func(o *Options) { o.fileFindFunc = fn }
}
// WithFileReadFunc sets the function that will return the
// content of template given the filename.
func WithFileReadFunc(fn FileReadFunc) Option {
return func(o *Options) { o.fileReadFunc = fn }
}
// WithFileReadOnRender forces template files to be read and
// parsed every time Render or Respond functions are called.
// This is useful for quickly reloading template files,
// but with a performance cost. This functionality
// is disabled by default.
func WithFileReadOnRender(yes bool) Option {
return func(o *Options) { o.fileReadOnRender = yes }
}
// WithTemplateFromFiles adds a template parsed from files.
func WithTemplateFromFiles(name string, files ...string) Option {
return func(o *Options) { o.files[name] = files }
}
// WithTemplatesFromFiles adds a map of templates parsed from files.
func WithTemplatesFromFiles(ts map[string][]string) Option {
return func(o *Options) {
for name, files := range ts {
o.files[name] = files
}
}
}
// WithTemplateFromStrings adds a template parsed from string.
func WithTemplateFromStrings(name string, strings ...string) Option {
return func(o *Options) { o.strings[name] = strings }
}
// WithTemplatesFromStrings adds a map of templates parsed from strings.
func WithTemplatesFromStrings(ts map[string][]string) Option {
return func(o *Options) {
for name, strings := range ts {
o.strings[name] = strings
}
}
}
// WithFunction adds a function to templates.
func WithFunction(name string, fn any) Option {
return func(o *Options) { o.functions[name] = fn }
}
// WithFunctions adds function map to templates.
func WithFunctions(fns template.FuncMap) Option {
return func(o *Options) {
for name, fn := range fns {
o.functions[name] = fn
}
}
}
// WithDelims sets the delimiters used in templates.
func WithDelims(open, close string) Option {
return func(o *Options) {
o.delimOpen = open
o.delimClose = close
}
}
// WithLogger sets the function that will perform message logging.
// Default is slog.Default().
func WithLogger(l *slog.Logger) Option {
return func(o *Options) { o.logger = l }
}
// Templates structure holds parsed templates.
type Templates struct {
templates map[string]*template.Template
parseFiles func(name string) (*template.Template, error)
contentType string
logger *slog.Logger
}
// New creates a new instance of Templates and parses
// provided files and strings.
func New(opts ...Option) (t *Templates, err error) {
functions := template.FuncMap{}
for name, fn := range defaultFunctions {
functions[name] = fn
}
o := &Options{
fileFindFunc: func(f string) string {
return f
},
fileReadFunc: os.ReadFile,
files: map[string][]string{},
functions: functions,
delimOpen: "{{",
delimClose: "}}",
logger: slog.Default(),
}
for _, opt := range opts {
opt(o)
}
t = &Templates{
templates: map[string]*template.Template{},
contentType: o.contentType,
logger: o.logger,
}
for name, strings := range o.strings {
tpl, err := parseStrings(template.New("").Funcs(o.functions).Delims(o.delimOpen, o.delimClose), strings...)
if err != nil {
return nil, err
}
t.templates[name] = tpl
}
parse := func(files []string) (tpl *template.Template, err error) {
fs := []string{}
for _, f := range files {
fs = append(fs, o.fileFindFunc(f))
}
return parseFiles(o.fileReadFunc, template.New("").Funcs(o.functions).Delims(o.delimOpen, o.delimClose), fs...)
}
if o.fileReadOnRender {
t.parseFiles = func(name string) (tpl *template.Template, err error) {
files, ok := o.files[name]
if !ok {
return nil, &Error{Err: ErrUnknownTemplate, Template: name}
}
return parse(files)
}
} else {
for name, files := range o.files {
tpl, err := parse(files)
if err != nil {
return nil, err
}
t.templates[name] = tpl
}
}
return
}
// RespondTemplateWithStatus executes a named template with provided data into buffer,
// then writes the the status and body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
func (t Templates) RespondTemplateWithStatus(w http.ResponseWriter, name, templateName string, data any, status int) {
tpl := t.mustTemplate(name)
buf := bytes.Buffer{}
if err := tpl.ExecuteTemplate(&buf, templateName, data); err != nil {
panic(err)
}
if t.contentType != "" {
w.Header().Set("Content-Type", t.contentType)
}
if status > 0 {
w.WriteHeader(status)
}
if _, err := buf.WriteTo(w); err != nil {
t.logger.Debug("templates: respond template with status", "name", name, "template", templateName, "status", status, "error", err)
}
}
// RespondWithStatus executes a template with provided data into buffer,
// then writes the the status and body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
func (t Templates) RespondWithStatus(w http.ResponseWriter, name string, data any, status int) {
tpl := t.mustTemplate(name)
buf := bytes.Buffer{}
if err := tpl.Execute(&buf, data); err != nil {
panic(err)
}
if t.contentType != "" {
w.Header().Set("Content-Type", t.contentType)
}
if status > 0 {
w.WriteHeader(status)
}
if _, err := buf.WriteTo(w); err != nil {
t.logger.Debug("templates: respond with status", "name", name, "status", status, "error", err)
}
}
// RespondTemplate executes a named template with provided data into buffer,
// then writes the the body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
func (t Templates) RespondTemplate(w http.ResponseWriter, name, templateName string, data any) {
t.RespondTemplateWithStatus(w, name, templateName, data, 0)
}
// Respond executes template with provided data into buffer,
// then writes the the body to the response writer.
// A panic will be raised if the template does not exist or fails to execute.
func (t Templates) Respond(w http.ResponseWriter, name string, data any) {
t.RespondWithStatus(w, name, data, 0)
}
// RenderTemplate executes a named template and returns the string.
func (t Templates) RenderTemplate(name, templateName string, data any) (s string, err error) {
tpl := t.mustTemplate(name)
buf := bytes.Buffer{}
if err := tpl.ExecuteTemplate(&buf, templateName, data); err != nil {
return "", err
}
return buf.String(), nil
}
// Render executes a template and returns the string.
func (t Templates) Render(name string, data any) (s string, err error) {
tpl := t.mustTemplate(name)
buf := bytes.Buffer{}
if err := tpl.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
func (t Templates) mustTemplate(name string) (tpl *template.Template) {
tpl, ok := t.templates[name]
if ok {
return tpl
}
if t.parseFiles != nil {
tpl, err := t.parseFiles(name)
if err != nil {
panic(err)
}
return tpl
}
panic(&Error{Err: ErrUnknownTemplate, Template: name})
}
func parseFiles(fn FileReadFunc, t *template.Template, filenames ...string) (*template.Template, error) {
for _, filename := range filenames {
b, err := fn(filename)
if err != nil {
return nil, fmt.Errorf("read template file %s: %v", filename, err)
}
_, err = t.Parse(string(b))
if err != nil {
return nil, fmt.Errorf("parse template file %s: %v", filename, err)
}
}
return t, nil
}
func parseStrings(t *template.Template, strings ...string) (*template.Template, error) {
for _, str := range strings {
_, err := t.Parse(str)
if err != nil {
return nil, err
}
}
return t, nil
}