forked from fasthttp-contrib/render
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
492 lines (422 loc) · 13.6 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
package render
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/valyala/fasthttp"
)
const (
// ContentBinary header value for binary data.
ContentBinary = "application/octet-stream"
// ContentHTML header value for HTML data.
ContentHTML = "text/html"
// ContentJS header value for JS data.
ContentJS = "text/javascript"
// 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"
)
// 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
}
// Config is a struct for specifying configuration options for the render.Render object.
type Config struct {
// Directories to load templates. Default is ["templates"].
Directories []string
// Directory - old way to change templates directory (deprecated, please use Directories property)
Directory string
// 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 [".html"].
Extensions []string
// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
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
// Gzip enable it if you want to render with gzip compression. Default is false
Gzip 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 of output to XHTML instead of HTML. Default is "text/html".
HTMLContentType string
// Allows changing of output to ECMAScript instead of JS. Default is "text/javascript".
JSContentType string
// If IsDevelopment is set to true, this will recompile the templates on every request. Default is false.
IsDevelopment bool
// Unescape HTML characters "&<>" to their original values. Default is false.
UnEscapeHTML bool
// 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
}
// 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 {
// Customize Secure with an Options struct.
config *Config
// Templates the *template.Template main object
Templates *template.Template
compiledCharset string
}
// New constructs a new Render instance with the supplied configs.
func New(config ...*Config) *Render {
var c *Config
if len(config) == 0 {
c = &Config{}
} else {
c = config[0]
}
r := &Render{
config: c,
}
r.Prepare()
return r
}
// Create constructs a new Render instance with the supplied configs. It doesn't build and prepare options yet, you should call the .Prepare for this.
func Create(config *Config) *Render {
return &Render{config: config}
}
// Prepare if
// Prepare must is called once before anything else inside the New(), this exists because for example Iris doesn't want to compile
// the templates on Render creation but after
func (r *Render) Prepare() {
r.prepareConfig()
if err := r.compileTemplates(); err != nil {
// We don't care about IsDevelopment, it's before server's run, panic
panic(err)
}
// Create a new buffer pool for writing templates into.
if bufPool == nil {
bufPool = NewBufferPool(64)
}
}
func (r *Render) prepareConfig() {
// Fill in the defaults if need be.
if len(r.config.Charset) == 0 {
r.config.Charset = defaultCharset
}
r.compiledCharset = "; charset=" + r.config.Charset
if len(r.config.Directory) != 0 {
r.config.Directories = []string{r.config.Directory}
}
if len(r.config.Directories) == 0 {
r.config.Directories = []string{"templates"}
}
if len(r.config.Extensions) == 0 {
r.config.Extensions = []string{".html"}
}
if len(r.config.HTMLContentType) == 0 {
r.config.HTMLContentType = ContentHTML
}
if len(r.config.JSContentType) == 0 {
r.config.JSContentType = ContentJS
}
}
func (r *Render) compileTemplates() error {
if r.config.Asset == nil || r.config.AssetNames == nil {
return r.compileTemplatesFromDir()
}
return r.compileTemplatesFromAsset()
}
func (r *Render) compileTemplatesFromDir() error {
var templateErr error
dirs := r.config.Directories
r.Templates = template.New("")
r.Templates.Delims(r.config.Delims.Left, r.config.Delims.Right)
for _, dir := range dirs {
// Walk the supplied directory and compile any files that match our extension list.
filepath.Walk(dir, func(path string, info os.FileInfo, err 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 || info.IsDir() {
return nil
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
ext := ""
if strings.Index(rel, ".") != -1 {
ext = filepath.Ext(rel)
}
for _, extension := range r.config.Extensions {
if ext == extension {
buf, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
name := (rel[0 : len(rel)-len(ext)])
tmpl := r.Templates.New(filepath.ToSlash(name))
// Add our funcmaps.
tmpl.Funcs(r.config.Funcs)
if !r.config.IsDevelopment {
//panic in production.
template.Must(tmpl.Funcs(helperFuncs).Parse(string(buf)))
} else {
if _, templateErr = tmpl.Funcs(helperFuncs).Parse(string(buf)); templateErr != nil {
break //we dont continue to the next templates
}
}
break
}
}
return nil
})
}
return templateErr
}
func (r *Render) compileTemplatesFromAsset() error {
var templateErr error
dirs := r.config.Directories
r.Templates = template.New(dirs[0])
r.Templates.Delims(r.config.Delims.Left, r.config.Delims.Right)
for _, path := range r.config.AssetNames() {
if !strings.HasPrefix(path, dirs[0]) {
continue
}
rel, err := filepath.Rel(dirs[0], path)
if err != nil {
panic(err)
}
ext := ""
if strings.Index(rel, ".") != -1 {
ext = "." + strings.Join(strings.Split(rel, ".")[1:], ".")
}
for _, extension := range r.config.Extensions {
if ext == extension {
buf, err := r.config.Asset(path)
if err != nil {
panic(err)
}
name := (rel[0 : len(rel)-len(ext)])
tmpl := r.Templates.New(filepath.ToSlash(name))
// Add our funcmaps.
tmpl.Funcs(r.config.Funcs)
if !r.config.IsDevelopment {
//panic in production.
template.Must(tmpl.Funcs(helperFuncs).Parse(string(buf)))
} else {
if _, templateErr = tmpl.Funcs(helperFuncs).Parse(string(buf)); templateErr != nil {
break //we dont continue to the next templates
}
}
break
}
}
}
return templateErr
}
// 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 {
return r.Templates.Lookup(t)
}
// Execute template by name
func (r *Render) Execute(name string, binding interface{}) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
return buf, r.Templates.ExecuteTemplate(buf, name, binding)
}
func (r *Render) addLayoutFuncs(name string, binding interface{}) {
funcs := template.FuncMap{
"yield": func() (template.HTML, error) {
buf, err := r.Execute(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
},
"partial": func(partialName string) (template.HTML, error) {
fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
if r.config.RequirePartials || r.TemplateLookup(fullPartialName) != nil {
buf, err := r.Execute(fullPartialName, binding)
// Return safe HTML here since we are rendering our own template.
return template.HTML(buf.String()), err
}
return "", nil
},
"render": func(fullPartialName string) (template.HTML, error) {
buf, err := r.Execute(fullPartialName, binding)
// Return safe HTML here since we are rendering our own template.
return template.HTML(buf.String()), err
},
}
if tpl := r.Templates.Lookup(name); tpl != nil {
tpl.Funcs(funcs)
}
}
func (r *Render) prepareHTMLLayout(layout []string) string {
if len(layout) > 0 {
return layout[0]
}
return r.config.Layout
}
// Render is the generic function called by XML, JSON, Data, HTML, and can be called by custom implementations.
func (r *Render) Render(ctx *fasthttp.RequestCtx, e Engine, data interface{}) error {
var err error
if r.config.Gzip {
err = e.RenderGzip(ctx, data)
} else {
err = e.Render(ctx, data)
}
if err != nil && !r.config.DisableHTTPErrorRendering {
ctx.Response.SetBodyString(err.Error())
ctx.Response.SetStatusCode(fasthttp.StatusInternalServerError)
}
return err
}
// Data writes out the raw bytes as binary data.
func (r *Render) Data(ctx *fasthttp.RequestCtx, status int, v []byte) error {
head := Head{
ContentType: ContentBinary,
Status: status,
}
d := Data{
Head: head,
}
return r.Render(ctx, d, v)
}
// HTML builds up the response from the specified template and bindings.
func (r *Render) HTML(ctx *fasthttp.RequestCtx, status int, name string, binding interface{}, layout ...string) error {
// If we are in development mode, recompile the templates on every HTML request.
if r.config.IsDevelopment {
if err := r.compileTemplates(); err != nil {
return err
}
}
layoutName := r.prepareHTMLLayout(layout)
// Assign a layout if there is one.
if len(layoutName) > 0 {
r.addLayoutFuncs(name, binding)
name = layoutName
}
head := Head{
ContentType: r.config.HTMLContentType + r.compiledCharset,
Status: status,
}
h := HTML{
Head: head,
Name: name,
Templates: r.Templates,
}
return r.Render(ctx, h, binding)
}
// JS builds up the response from the specified template and bindings.
func (r *Render) JS(ctx *fasthttp.RequestCtx, status int, name string, binding interface{}, layout ...string) error {
// If we are in development mode, recompile the templates on every JS request.
if r.config.IsDevelopment {
if err := r.compileTemplates(); err != nil {
return err
}
}
layoutName := r.prepareHTMLLayout(layout)
// Assign a layout if there is one.
if len(layoutName) > 0 {
r.addLayoutFuncs(name, binding)
name = layoutName
}
head := Head{
ContentType: r.config.JSContentType + r.compiledCharset,
Status: status,
}
h := HTML{
Head: head,
Name: name,
Templates: r.Templates,
}
return r.Render(ctx, h, binding)
}
// JSON marshals the given interface object and writes the JSON response.
func (r *Render) JSON(ctx *fasthttp.RequestCtx, status int, v interface{}) error {
head := Head{
ContentType: ContentJSON + r.compiledCharset,
Status: status,
}
j := JSON{
Head: head,
Indent: r.config.IndentJSON,
Prefix: r.config.PrefixJSON,
UnEscapeHTML: r.config.UnEscapeHTML,
StreamingJSON: r.config.StreamingJSON,
}
return r.Render(ctx, j, v)
}
// JSONP marshals the given interface object and writes the JSON response.
func (r *Render) JSONP(ctx *fasthttp.RequestCtx, status int, callback string, v interface{}) error {
head := Head{
ContentType: ContentJSONP + r.compiledCharset,
Status: status,
}
j := JSONP{
Head: head,
Indent: r.config.IndentJSON,
Callback: callback,
}
return r.Render(ctx, j, v)
}
// Text writes out a string as plain text.
func (r *Render) Text(ctx *fasthttp.RequestCtx, status int, v string) error {
head := Head{
ContentType: ContentText + r.compiledCharset,
Status: status,
}
t := Text{
Head: head,
}
return r.Render(ctx, t, v)
}
// XML marshals the given interface object and writes the XML response.
func (r *Render) XML(ctx *fasthttp.RequestCtx, status int, v interface{}) error {
head := Head{
ContentType: ContentXML + r.compiledCharset,
Status: status,
}
x := XML{
Head: head,
Indent: r.config.IndentXML,
Prefix: r.config.PrefixXML,
}
return r.Render(ctx, x, v)
}