-
Notifications
You must be signed in to change notification settings - Fork 146
/
render.go
596 lines (499 loc) · 15.8 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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package render
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
)
const (
// ContentBinary header value for binary data.
ContentBinary = "application/octet-stream"
// ContentHTML header value for HTML data.
ContentHTML = "text/html"
// ContentJSON header value for JSON data.
ContentJSON = "application/json"
// ContentJSONP header value for JSONP data.
ContentJSONP = "application/javascript"
// ContentLength header constant.
ContentLength = "Content-Length"
// ContentText header value for Text data.
ContentText = "text/plain"
// ContentType header constant.
ContentType = "Content-Type"
// ContentXHTML header value for XHTML data.
ContentXHTML = "application/xhtml+xml"
// ContentXML header value for XML data.
ContentXML = "text/xml"
// Default character encoding.
defaultCharset = "UTF-8"
// Buffer pool size.
bufferPoolSize = 32
// Buffer pool capacity.
bufferPoolCapacity = 1 << 19
)
// helperFuncs had to be moved out. See helpers.go|helpers_pre16.go files.
// Delims represents a set of Left and Right delimiters for HTML template rendering.
type Delims struct {
// Left delimiter, defaults to {{.
Left string
// Right delimiter, defaults to }}.
Right string
}
// Options is a struct for specifying configuration options for the render.Render object.
type Options struct {
// Directory to load templates. Default is "templates".
Directory string
// FileSystem to access files
FileSystem FileSystem
// Asset function to use in place of directory. Defaults to nil.
Asset func(name string) ([]byte, error)
// AssetNames function to use in place of directory. Defaults to nil.
AssetNames func() []string
// Layout template name. Will not render a layout if blank (""). Defaults to blank ("").
Layout string
// Extensions to parse template files from. Defaults to [".tmpl"].
Extensions []string
// Funcs is a slice of FuncMaps to apply to the template upon compilation.
// This is useful for helper functions. Defaults to empty map.
Funcs []template.FuncMap
// Delims sets the action delimiters to the specified strings in the Delims struct.
Delims Delims
// Appends the given character set to the Content-Type header. Default is "UTF-8".
Charset string
// If DisableCharset is set to true, it will not append the above Charset value to the Content-Type header.
// Default is false.
DisableCharset bool
// Outputs human readable JSON.
IndentJSON bool
// Outputs human readable XML. Default is false.
IndentXML bool
// Prefixes the JSON output with the given bytes. Default is false.
PrefixJSON []byte
// Prefixes the XML output with the given bytes.
PrefixXML []byte
// Allows changing the binary content type.
BinaryContentType string
// Allows changing the HTML content type.
HTMLContentType string
// Allows changing the JSON content type.
JSONContentType string
// Allows changing the JSONP content type.
JSONPContentType string
// Allows changing the Text content type.
TextContentType string
// Allows changing the XML content type.
XMLContentType string
// If IsDevelopment is set to true, this will recompile the templates on every request. Default is false.
IsDevelopment bool
// If UseMutexLock is set to true, the standard `sync.RWMutex` lock will be used instead of the lock free
// implementation. Default is false. Note that when `IsDevelopment` is true, the standard `sync.RWMutex`
// lock is always used. Lock free is only a production feature.
UseMutexLock bool
// Unescape HTML characters "&<>" to their original values. Default is false.
UnEscapeHTML bool
// Sets the `Option` value for HTML templates. Defaults to blank ("").
HTMLTemplateOption string
// Streams JSON responses instead of marshalling prior to sending. Default is false.
StreamingJSON bool
// Require that all partials executed in the layout are implemented in all templates using the layout.
// Default is false.
RequirePartials bool
// Deprecated: Use the above `RequirePartials` instead of this. As of Go 1.6, blocks are built in. Default is false.
RequireBlocks bool
// Disables automatic rendering of http.StatusInternalServerError when an error occurs. Default is false.
DisableHTTPErrorRendering bool
// Enables using partials without the current filename suffix which allows use of the same template in
// multiple files. e.g {{ partial "carousel" }} inside the home template will match carousel-home or carousel.
// ***NOTE*** - This option should be named RenderPartialsWithoutSuffix as that is what it does.
// "Prefix" is a typo. Maintaining the existing name for backwards compatibility.
RenderPartialsWithoutPrefix bool
// BufferPool to use when rendering HTML templates. If none is supplied
// defaults to SizedBufferPool of size 32 with 512KiB buffers.
BufferPool GenericBufferPool
// Custom JSON Encoder. Defaults to encoding/json.NewEncoder.
JSONEncoder func(w io.Writer) JSONEncoder
}
// HTMLOptions is a struct for overriding some rendering Options for specific HTML call.
type HTMLOptions struct {
// Layout template name. Overrides Options.Layout.
Layout string
// Funcs added to Options.Funcs.
Funcs template.FuncMap
}
// Render is a service that provides functions for easily writing JSON, XML,
// binary data, and HTML templates out to a HTTP Response.
type Render struct {
lock rwLock
// Customize Secure with an Options struct.
opt Options
templates *template.Template
compiledCharset string
hasWatcher bool
}
// New constructs a new Render instance with the supplied options.
func New(options ...Options) *Render {
var o Options
if len(options) > 0 {
o = options[0]
}
r := Render{opt: o}
r.prepareOptions()
r.CompileTemplates()
return &r
}
func (r *Render) prepareOptions() {
// Fill in the defaults if need be.
if len(r.opt.Charset) == 0 {
r.opt.Charset = defaultCharset
}
if !r.opt.DisableCharset {
r.compiledCharset = "; charset=" + r.opt.Charset
}
if len(r.opt.Directory) == 0 {
r.opt.Directory = "templates"
}
if r.opt.FileSystem == nil {
r.opt.FileSystem = &LocalFileSystem{}
}
if len(r.opt.Extensions) == 0 {
r.opt.Extensions = []string{".tmpl"}
}
if len(r.opt.BinaryContentType) == 0 {
r.opt.BinaryContentType = ContentBinary
}
if len(r.opt.HTMLContentType) == 0 {
r.opt.HTMLContentType = ContentHTML
}
if len(r.opt.JSONContentType) == 0 {
r.opt.JSONContentType = ContentJSON
}
if len(r.opt.JSONPContentType) == 0 {
r.opt.JSONPContentType = ContentJSONP
}
if len(r.opt.TextContentType) == 0 {
r.opt.TextContentType = ContentText
}
if len(r.opt.XMLContentType) == 0 {
r.opt.XMLContentType = ContentXML
}
if r.opt.BufferPool == nil {
r.opt.BufferPool = NewSizedBufferPool(bufferPoolSize, bufferPoolCapacity)
}
if r.opt.IsDevelopment || r.opt.UseMutexLock {
r.lock = &sync.RWMutex{}
} else {
r.lock = &emptyLock{}
}
if r.opt.JSONEncoder == nil {
r.opt.JSONEncoder = func(w io.Writer) JSONEncoder {
return json.NewEncoder(w)
}
}
}
func (r *Render) CompileTemplates() {
if r.opt.Asset == nil || r.opt.AssetNames == nil {
r.compileTemplatesFromDir()
return
}
r.compileTemplatesFromAsset()
}
func (r *Render) compileTemplatesFromDir() {
dir := r.opt.Directory
tmpTemplates := template.New(dir)
if len(r.opt.HTMLTemplateOption) > 0 {
tmpTemplates.Option(r.opt.HTMLTemplateOption)
}
tmpTemplates.Delims(r.opt.Delims.Left, r.opt.Delims.Right)
var watcher *fsnotify.Watcher
if r.opt.IsDevelopment {
var err error
watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Printf("Unable to create new watcher for template files. "+
"Templates will be recompiled on every render. Error: %v\n", err)
}
}
// Walk the supplied directory and compile any files that match our extension list.
_ = r.opt.FileSystem.Walk(dir, func(path string, info os.FileInfo, _ error) error {
// Fix same-extension-dirs bug: some dir might be named to: "users.tmpl", "local.html".
// These dirs should be excluded as they are not valid golang templates, but files under
// them should be treat as normal.
// If is a dir, return immediately (dir is not a valid golang template).
if info != nil && watcher != nil {
_ = watcher.Add(path)
}
if info == nil || info.IsDir() {
return nil
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
ext := ""
if strings.Contains(rel, ".") {
ext = filepath.Ext(rel)
}
for _, extension := range r.opt.Extensions {
if ext == extension {
buf, err := r.opt.FileSystem.ReadFile(path)
if err != nil {
panic(err)
}
name := (rel[0 : len(rel)-len(ext)])
tmpl := tmpTemplates.New(filepath.ToSlash(name))
// Add our funcmaps.
for _, funcs := range r.opt.Funcs {
tmpl.Funcs(funcs)
}
// Break out if this parsing fails. We don't want any silent server starts.
template.Must(tmpl.Funcs(helperFuncs()).Parse(string(buf)))
break
}
}
return nil
})
r.lock.Lock()
defer r.lock.Unlock()
r.templates = tmpTemplates
if r.hasWatcher = watcher != nil; r.hasWatcher {
go func() {
select {
case _, ok := <-watcher.Events:
if !ok {
return
}
case _, ok := <-watcher.Errors:
if !ok {
return
}
}
watcher.Close()
r.CompileTemplates()
}()
}
}
func (r *Render) compileTemplatesFromAsset() {
dir := r.opt.Directory
tmpTemplates := template.New(dir)
if len(r.opt.HTMLTemplateOption) > 0 {
tmpTemplates.Option(r.opt.HTMLTemplateOption)
}
tmpTemplates.Delims(r.opt.Delims.Left, r.opt.Delims.Right)
for _, path := range r.opt.AssetNames() {
if !strings.HasPrefix(path, dir) {
continue
}
rel, err := filepath.Rel(dir, path)
if err != nil {
panic(err)
}
ext := ""
if strings.Contains(rel, ".") {
ext = "." + strings.Join(strings.Split(rel, ".")[1:], ".")
}
for _, extension := range r.opt.Extensions {
if ext == extension {
buf, err := r.opt.Asset(path)
if err != nil {
panic(err)
}
name := (rel[0 : len(rel)-len(ext)])
tmpl := tmpTemplates.New(filepath.ToSlash(name))
// Add our funcmaps.
for _, funcs := range r.opt.Funcs {
tmpl.Funcs(funcs)
}
// Break out if this parsing fails. We don't want any silent server starts.
template.Must(tmpl.Funcs(helperFuncs()).Parse(string(buf)))
break
}
}
}
r.lock.Lock()
defer r.lock.Unlock()
r.templates = tmpTemplates
}
// TemplateLookup is a wrapper around template.Lookup and returns
// the template with the given name that is associated with t, or nil
// if there is no such template.
func (r *Render) TemplateLookup(t string) *template.Template {
r.lock.RLock()
defer r.lock.RUnlock()
return r.templates.Lookup(t)
}
func (r *Render) execute(templates *template.Template, name string, binding interface{}) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
return buf, templates.ExecuteTemplate(buf, name, binding)
}
func (r *Render) layoutFuncs(templates *template.Template, name string, binding interface{}) template.FuncMap {
return template.FuncMap{
"yield": func() (template.HTML, error) {
buf, err := r.execute(templates, name, binding)
// Return safe HTML here since we are rendering our own template.
return template.HTML(buf.String()), err
},
"current": func() (string, error) {
return name, nil
},
"block": func(partialName string) (template.HTML, error) {
log.Println("Render's `block` implementation is now depericated. Use `partial` as a drop in replacement.")
fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
if templates.Lookup(fullPartialName) == nil && r.opt.RenderPartialsWithoutPrefix {
fullPartialName = partialName
}
if r.opt.RequireBlocks || templates.Lookup(fullPartialName) != nil {
buf, err := r.execute(templates, fullPartialName, binding)
// Return safe HTML here since we are rendering our own template.
return template.HTML(buf.String()), err
}
return "", nil
},
"partial": func(partialName string) (template.HTML, error) {
fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
if templates.Lookup(fullPartialName) == nil && r.opt.RenderPartialsWithoutPrefix {
fullPartialName = partialName
}
if r.opt.RequirePartials || templates.Lookup(fullPartialName) != nil {
buf, err := r.execute(templates, fullPartialName, binding)
// Return safe HTML here since we are rendering our own template.
return template.HTML(buf.String()), err
}
return "", nil
},
}
}
func (r *Render) prepareHTMLOptions(htmlOpt []HTMLOptions) HTMLOptions {
layout := r.opt.Layout
funcs := template.FuncMap{}
for _, tmp := range r.opt.Funcs {
for k, v := range tmp {
funcs[k] = v
}
}
if len(htmlOpt) > 0 {
opt := htmlOpt[0]
if len(opt.Layout) > 0 {
layout = opt.Layout
}
for k, v := range opt.Funcs {
funcs[k] = v
}
}
return HTMLOptions{
Layout: layout,
Funcs: funcs,
}
}
// Render is the generic function called by XML, JSON, Data, HTML, and can be called by custom implementations.
func (r *Render) Render(w io.Writer, e Engine, data interface{}) error {
err := e.Render(w, data)
if hw, ok := w.(http.ResponseWriter); err != nil && !r.opt.DisableHTTPErrorRendering && ok {
http.Error(hw, err.Error(), http.StatusInternalServerError)
}
return err
}
// Data writes out the raw bytes as binary data.
func (r *Render) Data(w io.Writer, status int, v []byte) error {
head := Head{
ContentType: r.opt.BinaryContentType,
Status: status,
}
d := Data{
Head: head,
}
return r.Render(w, d, v)
}
// HTML builds up the response from the specified template and bindings.
func (r *Render) HTML(w io.Writer, status int, name string, binding interface{}, htmlOpt ...HTMLOptions) error {
// If we are in development mode, recompile the templates on every HTML request.
r.lock.RLock() // rlock here because we're reading the hasWatcher
if r.opt.IsDevelopment && !r.hasWatcher {
r.lock.RUnlock() // runlock here because CompileTemplates will lock
r.CompileTemplates()
r.lock.RLock()
}
templates := r.templates
r.lock.RUnlock()
opt := r.prepareHTMLOptions(htmlOpt)
if tpl := templates.Lookup(name); tpl != nil {
if len(opt.Layout) > 0 {
tpl.Funcs(r.layoutFuncs(templates, name, binding))
name = opt.Layout
}
if len(opt.Funcs) > 0 {
tpl.Funcs(opt.Funcs)
}
}
head := Head{
ContentType: r.opt.HTMLContentType + r.compiledCharset,
Status: status,
}
h := HTML{
Head: head,
Name: name,
Templates: templates,
bp: r.opt.BufferPool,
}
return r.Render(w, h, binding)
}
// JSON marshals the given interface object and writes the JSON response.
func (r *Render) JSON(w io.Writer, status int, v interface{}) error {
head := Head{
ContentType: r.opt.JSONContentType + r.compiledCharset,
Status: status,
}
j := JSON{
Head: head,
Indent: r.opt.IndentJSON,
Prefix: r.opt.PrefixJSON,
UnEscapeHTML: r.opt.UnEscapeHTML,
StreamingJSON: r.opt.StreamingJSON,
Encoder: r.opt.JSONEncoder,
}
return r.Render(w, j, v)
}
// JSONP marshals the given interface object and writes the JSON response.
func (r *Render) JSONP(w io.Writer, status int, callback string, v interface{}) error {
head := Head{
ContentType: r.opt.JSONPContentType + r.compiledCharset,
Status: status,
}
j := JSONP{
Head: head,
Indent: r.opt.IndentJSON,
Callback: callback,
}
return r.Render(w, j, v)
}
// Text writes out a string as plain text.
func (r *Render) Text(w io.Writer, status int, v string) error {
head := Head{
ContentType: r.opt.TextContentType + r.compiledCharset,
Status: status,
}
t := Text{
Head: head,
}
return r.Render(w, t, v)
}
// XML marshals the given interface object and writes the XML response.
func (r *Render) XML(w io.Writer, status int, v interface{}) error {
head := Head{
ContentType: r.opt.XMLContentType + r.compiledCharset,
Status: status,
}
x := XML{
Head: head,
Indent: r.opt.IndentXML,
Prefix: r.opt.PrefixXML,
}
return r.Render(w, x, v)
}