Debian Codegraph @

render.go

raw symbols SCIP
1 package render
2
3 import (
4 "bytes"
5 "fmt"
6 "html/template"
7 "io"
8 "log"
9 "net/http"
10 "os"
11 "path/filepath"
12 "strings"
13 "sync"
14
15 "github.com/fsnotify/fsnotify"
16 )
17
18 const (
19 // ContentBinary header value for binary data.
20 ContentBinary = "application/octet-stream"
21 // ContentHTML header value for HTML data.
22 ContentHTML = "text/html"
23 // ContentJSON header value for JSON data.
24 ContentJSON = "application/json"
25 // ContentJSONP header value for JSONP data.
26 ContentJSONP = "application/javascript"
27 // ContentLength header constant.
28 ContentLength = "Content-Length"
29 // ContentText header value for Text data.
30 ContentText = "text/plain"
31 // ContentType header constant.
32 ContentType = "Content-Type"
33 // ContentXHTML header value for XHTML data.
34 ContentXHTML = "application/xhtml+xml"
35 // ContentXML header value for XML data.
36 ContentXML = "text/xml"
37 // Default character encoding.
38 defaultCharset = "UTF-8"
39 )
40
41 // helperFuncs had to be moved out. See helpers.go|helpers_pre16.go files.
42
43 // Delims represents a set of Left and Right delimiters for HTML template rendering.
44 type Delims struct {
45 // Left delimiter, defaults to {{.
46 Left string
47 // Right delimiter, defaults to }}.
48 Right string
49 }
50
51 // Options is a struct for specifying configuration options for the render.Render object.
52 type Options struct {
53 // Directory to load templates. Default is "templates".
54 Directory string
55 // FileSystem to access files
56 FileSystem FileSystem
57 // Asset function to use in place of directory. Defaults to nil.
58 Asset func(name string) ([]byte, error)
59 // AssetNames function to use in place of directory. Defaults to nil.
60 AssetNames func() []string
61 // Layout template name. Will not render a layout if blank (""). Defaults to blank ("").
62 Layout string
63 // Extensions to parse template files from. Defaults to [".tmpl"].
64 Extensions []string
65 // Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to empty map.
66 Funcs []template.FuncMap
67 // Delims sets the action delimiters to the specified strings in the Delims struct.
68 Delims Delims
69 // Appends the given character set to the Content-Type header. Default is "UTF-8".
70 Charset string
71 // If DisableCharset is set to true, it will not append the above Charset value to the Content-Type header. Default is false.
72 DisableCharset bool
73 // Outputs human readable JSON.
74 IndentJSON bool
75 // Outputs human readable XML. Default is false.
76 IndentXML bool
77 // Prefixes the JSON output with the given bytes. Default is false.
78 PrefixJSON []byte
79 // Prefixes the XML output with the given bytes.
80 PrefixXML []byte
81 // Allows changing the binary content type.
82 BinaryContentType string
83 // Allows changing the HTML content type.
84 HTMLContentType string
85 // Allows changing the JSON content type.
86 JSONContentType string
87 // Allows changing the JSONP content type.
88 JSONPContentType string
89 // Allows changing the Text content type.
90 TextContentType string
91 // Allows changing the XML content type.
92 XMLContentType string
93 // If IsDevelopment is set to true, this will recompile the templates on every request. Default is false.
94 IsDevelopment bool
95 // If UseMutexLock is set to true, the standard `sync.RWMutex` lock will be used instead of the lock free implementation. Default is false.
96 // Note that when `IsDevelopment` is true, the standard `sync.RWMutex` lock is always used. Lock free is only a production feature.
97 UseMutexLock bool
98 // Unescape HTML characters "&<>" to their original values. Default is false.
99 UnEscapeHTML bool
100 // Streams JSON responses instead of marshalling prior to sending. Default is false.
101 StreamingJSON bool
102 // Require that all partials executed in the layout are implemented in all templates using the layout. Default is false.
103 RequirePartials bool
104 // Deprecated: Use the above `RequirePartials` instead of this. As of Go 1.6, blocks are built in. Default is false.
105 RequireBlocks bool
106 // Disables automatic rendering of http.StatusInternalServerError when an error occurs. Default is false.
107 DisableHTTPErrorRendering bool
108 // Enables using partials without the current filename suffix which allows use of the same template in multiple files. e.g {{ partial "carosuel" }} inside the home template will match carosel-home or carosel.
109 // ***NOTE*** - This option should be named RenderPartialsWithoutSuffix as that is what it does. "Prefix" is a typo. Maintaining the existing name for backwards compatibility.
110 RenderPartialsWithoutPrefix bool
111 // BufferPool to use when rendering HTML templates. If none is supplied
112 // defaults to SizedBufferPool of size 32 with 512KiB buffers.
113 BufferPool GenericBufferPool
114 }
115
116 // HTMLOptions is a struct for overriding some rendering Options for specific HTML call.
117 type HTMLOptions struct {
118 // Layout template name. Overrides Options.Layout.
119 Layout string
120 // Funcs added to Options.Funcs.
121 Funcs template.FuncMap
122 }
123
124 // Render is a service that provides functions for easily writing JSON, XML,
125 // binary data, and HTML templates out to a HTTP Response.
126 type Render struct {
127 lock rwLock
128
129 // Customize Secure with an Options struct.
130 opt Options
131 templates *template.Template
132 compiledCharset string
133 hasWatcher bool
134 }
135
136 // New constructs a new Render instance with the supplied options.
137 func New(options ...Options) *Render {
138 var o Options
139 if len(options) > 0 {
140 o = options[0]
141 }
142
143 r := Render{opt: o}
144
145 r.prepareOptions()
146 r.CompileTemplates()
147
148 return &r
149 }
150
151 func (r *Render) prepareOptions() {
152 // Fill in the defaults if need be.
153 if len(r.opt.Charset) == 0 {
154 r.opt.Charset = defaultCharset
155 }
156 if !r.opt.DisableCharset {
157 r.compiledCharset = "; charset=" + r.opt.Charset
158 }
159 if len(r.opt.Directory) == 0 {
160 r.opt.Directory = "templates"
161 }
162 if r.opt.FileSystem == nil {
163 r.opt.FileSystem = &LocalFileSystem{}
164 }
165 if len(r.opt.Extensions) == 0 {
166 r.opt.Extensions = []string{".tmpl"}
167 }
168 if len(r.opt.BinaryContentType) == 0 {
169 r.opt.BinaryContentType = ContentBinary
170 }
171 if len(r.opt.HTMLContentType) == 0 {
172 r.opt.HTMLContentType = ContentHTML
173 }
174 if len(r.opt.JSONContentType) == 0 {
175 r.opt.JSONContentType = ContentJSON
176 }
177 if len(r.opt.JSONPContentType) == 0 {
178 r.opt.JSONPContentType = ContentJSONP
179 }
180 if len(r.opt.TextContentType) == 0 {
181 r.opt.TextContentType = ContentText
182 }
183 if len(r.opt.XMLContentType) == 0 {
184 r.opt.XMLContentType = ContentXML
185 }
186 if r.opt.BufferPool == nil {
187 r.opt.BufferPool = NewSizedBufferPool(32, 1<<19) // 32 buffers of size 512KiB each
188 }
189 if r.opt.IsDevelopment || r.opt.UseMutexLock {
190 r.lock = &sync.RWMutex{}
191 } else {
192 r.lock = &emptyLock{}
193 }
194 }
195
196 func (r *Render) CompileTemplates() {
197 if r.opt.Asset == nil || r.opt.AssetNames == nil {
198 r.compileTemplatesFromDir()
199 return
200 }
201
202 r.compileTemplatesFromAsset()
203 }
204
205 func (r *Render) compileTemplatesFromDir() {
206 dir := r.opt.Directory
207 tmpTemplates := template.New(dir)
208 tmpTemplates.Delims(r.opt.Delims.Left, r.opt.Delims.Right)
209
210 var watcher *fsnotify.Watcher
211 if r.opt.IsDevelopment {
212 var err error
213 watcher, err = fsnotify.NewWatcher()
214 if err != nil {
215 log.Printf("Unable to create new watcher for template files. Templates will be recompiled on every render. Error: %v\n", err)
216 }
217 }
218
219 // Walk the supplied directory and compile any files that match our extension list.
220 _ = r.opt.FileSystem.Walk(dir, func(path string, info os.FileInfo, _ error) error {
221 // Fix same-extension-dirs bug: some dir might be named to: "users.tmpl", "local.html".
222 // These dirs should be excluded as they are not valid golang templates, but files under
223 // them should be treat as normal.
224 // If is a dir, return immediately (dir is not a valid golang template).
225 if info != nil && watcher != nil {
226 _ = watcher.Add(path)
227 }
228 if info == nil || info.IsDir() {
229 return nil
230 }
231
232 rel, err := filepath.Rel(dir, path)
233 if err != nil {
234 return err
235 }
236
237 ext := ""
238 if strings.Contains(rel, ".") {
239 ext = filepath.Ext(rel)
240 }
241
242 for _, extension := range r.opt.Extensions {
243 if ext == extension {
244 buf, err := r.opt.FileSystem.ReadFile(path)
245 if err != nil {
246 panic(err)
247 }
248
249 name := (rel[0 : len(rel)-len(ext)])
250 tmpl := tmpTemplates.New(filepath.ToSlash(name))
251
252 // Add our funcmaps.
253 for _, funcs := range r.opt.Funcs {
254 tmpl.Funcs(funcs)
255 }
256
257 // Break out if this parsing fails. We don't want any silent server starts.
258 template.Must(tmpl.Funcs(helperFuncs).Parse(string(buf)))
259 break
260 }
261 }
262 return nil
263 })
264
265 r.lock.Lock()
266 defer r.lock.Unlock()
267 r.templates = tmpTemplates
268 if r.hasWatcher = watcher != nil; r.hasWatcher {
269 go func() {
270 select {
271 case _, ok := <-watcher.Events:
272 if !ok {
273 return
274 }
275 case _, ok := <-watcher.Errors:
276 if !ok {
277 return
278 }
279 }
280 watcher.Close()
281 r.CompileTemplates()
282 }()
283 }
284 }
285
286 func (r *Render) compileTemplatesFromAsset() {
287 dir := r.opt.Directory
288 tmpTemplates := template.New(dir)
289 tmpTemplates.Delims(r.opt.Delims.Left, r.opt.Delims.Right)
290
291 for _, path := range r.opt.AssetNames() {
292 if !strings.HasPrefix(path, dir) {
293 continue
294 }
295
296 rel, err := filepath.Rel(dir, path)
297 if err != nil {
298 panic(err)
299 }
300
301 ext := ""
302 if strings.Contains(rel, ".") {
303 ext = "." + strings.Join(strings.Split(rel, ".")[1:], ".")
304 }
305
306 for _, extension := range r.opt.Extensions {
307 if ext == extension {
308 buf, err := r.opt.Asset(path)
309 if err != nil {
310 panic(err)
311 }
312
313 name := (rel[0 : len(rel)-len(ext)])
314 tmpl := tmpTemplates.New(filepath.ToSlash(name))
315
316 // Add our funcmaps.
317 for _, funcs := range r.opt.Funcs {
318 tmpl.Funcs(funcs)
319 }
320
321 // Break out if this parsing fails. We don't want any silent server starts.
322 template.Must(tmpl.Funcs(helperFuncs).Parse(string(buf)))
323 break
324 }
325 }
326 }
327 r.lock.Lock()
328 defer r.lock.Unlock()
329 r.templates = tmpTemplates
330 }
331
332 // TemplateLookup is a wrapper around template.Lookup and returns
333 // the template with the given name that is associated with t, or nil
334 // if there is no such template.
335 func (r *Render) TemplateLookup(t string) *template.Template {
336 r.lock.RLock()
337 defer r.lock.RUnlock()
338 return r.templates.Lookup(t)
339 }
340
341 func (r *Render) execute(templates *template.Template, name string, binding interface{}) (*bytes.Buffer, error) {
342 buf := new(bytes.Buffer)
343 return buf, templates.ExecuteTemplate(buf, name, binding)
344 }
345
346 func (r *Render) layoutFuncs(templates *template.Template, name string, binding interface{}) template.FuncMap {
347 return template.FuncMap{
348 "yield": func() (template.HTML, error) {
349 buf, err := r.execute(templates, name, binding)
350 // Return safe HTML here since we are rendering our own template.
351 return template.HTML(buf.String()), err
352 },
353 "current": func() (string, error) {
354 return name, nil
355 },
356 "block": func(partialName string) (template.HTML, error) {
357 log.Println("Render's `block` implementation is now depericated. Use `partial` as a drop in replacement.")
358 fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
359 if templates.Lookup(fullPartialName) == nil && r.opt.RenderPartialsWithoutPrefix {
360 fullPartialName = partialName
361 }
362 if r.opt.RequireBlocks || templates.Lookup(fullPartialName) != nil {
363 buf, err := r.execute(templates, fullPartialName, binding)
364 // Return safe HTML here since we are rendering our own template.
365 return template.HTML(buf.String()), err
366 }
367 return "", nil
368 },
369 "partial": func(partialName string) (template.HTML, error) {
370 fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
371 if templates.Lookup(fullPartialName) == nil && r.opt.RenderPartialsWithoutPrefix {
372 fullPartialName = partialName
373 }
374 if r.opt.RequirePartials || templates.Lookup(fullPartialName) != nil {
375 buf, err := r.execute(templates, fullPartialName, binding)
376 // Return safe HTML here since we are rendering our own template.
377 return template.HTML(buf.String()), err
378 }
379 return "", nil
380 },
381 }
382 }
383
384 func (r *Render) prepareHTMLOptions(htmlOpt []HTMLOptions) HTMLOptions {
385 layout := r.opt.Layout
386 funcs := template.FuncMap{}
387
388 for _, tmp := range r.opt.Funcs {
389 for k, v := range tmp {
390 funcs[k] = v
391 }
392 }
393
394 if len(htmlOpt) > 0 {
395 opt := htmlOpt[0]
396 if len(opt.Layout) > 0 {
397 layout = opt.Layout
398 }
399
400 for k, v := range opt.Funcs {
401 funcs[k] = v
402 }
403 }
404
405 return HTMLOptions{
406 Layout: layout,
407 Funcs: funcs,
408 }
409 }
410
411 // Render is the generic function called by XML, JSON, Data, HTML, and can be called by custom implementations.
412 func (r *Render) Render(w io.Writer, e Engine, data interface{}) error {
413 err := e.Render(w, data)
414 if hw, ok := w.(http.ResponseWriter); err != nil && !r.opt.DisableHTTPErrorRendering && ok {
415 http.Error(hw, err.Error(), http.StatusInternalServerError)
416 }
417 return err
418 }
419
420 // Data writes out the raw bytes as binary data.
421 func (r *Render) Data(w io.Writer, status int, v []byte) error {
422 head := Head{
423 ContentType: r.opt.BinaryContentType,
424 Status: status,
425 }
426
427 d := Data{
428 Head: head,
429 }
430
431 return r.Render(w, d, v)
432 }
433
434 // HTML builds up the response from the specified template and bindings.
435 func (r *Render) HTML(w io.Writer, status int, name string, binding interface{}, htmlOpt ...HTMLOptions) error {
436 // If we are in development mode, recompile the templates on every HTML request.
437 r.lock.RLock() // rlock here because we're reading the hasWatcher
438 if r.opt.IsDevelopment && !r.hasWatcher {
439 r.lock.RUnlock() // runlock here because CompileTemplates will lock
440 r.CompileTemplates()
441 r.lock.RLock()
442 }
443 templates := r.templates
444 r.lock.RUnlock()
445
446 opt := r.prepareHTMLOptions(htmlOpt)
447 if tpl := templates.Lookup(name); tpl != nil {
448 if len(opt.Layout) > 0 {
449 tpl.Funcs(r.layoutFuncs(templates, name, binding))
450 name = opt.Layout
451 }
452
453 if len(opt.Funcs) > 0 {
454 tpl.Funcs(opt.Funcs)
455 }
456 }
457
458 head := Head{
459 ContentType: r.opt.HTMLContentType + r.compiledCharset,
460 Status: status,
461 }
462
463 h := HTML{
464 Head: head,
465 Name: name,
466 Templates: templates,
467 bp: r.opt.BufferPool,
468 }
469
470 return r.Render(w, h, binding)
471 }
472
473 // JSON marshals the given interface object and writes the JSON response.
474 func (r *Render) JSON(w io.Writer, status int, v interface{}) error {
475 head := Head{
476 ContentType: r.opt.JSONContentType + r.compiledCharset,
477 Status: status,
478 }
479
480 j := JSON{
481 Head: head,
482 Indent: r.opt.IndentJSON,
483 Prefix: r.opt.PrefixJSON,
484 UnEscapeHTML: r.opt.UnEscapeHTML,
485 StreamingJSON: r.opt.StreamingJSON,
486 }
487
488 return r.Render(w, j, v)
489 }
490
491 // JSONP marshals the given interface object and writes the JSON response.
492 func (r *Render) JSONP(w io.Writer, status int, callback string, v interface{}) error {
493 head := Head{
494 ContentType: r.opt.JSONPContentType + r.compiledCharset,
495 Status: status,
496 }
497
498 j := JSONP{
499 Head: head,
500 Indent: r.opt.IndentJSON,
501 Callback: callback,
502 }
503
504 return r.Render(w, j, v)
505 }
506
507 // Text writes out a string as plain text.
508 func (r *Render) Text(w io.Writer, status int, v string) error {
509 head := Head{
510 ContentType: r.opt.TextContentType + r.compiledCharset,
511 Status: status,
512 }
513
514 t := Text{
515 Head: head,
516 }
517
518 return r.Render(w, t, v)
519 }
520
521 // XML marshals the given interface object and writes the XML response.
522 func (r *Render) XML(w io.Writer, status int, v interface{}) error {
523 head := Head{
524 ContentType: r.opt.XMLContentType + r.compiledCharset,
525 Status: status,
526 }
527
528 x := XML{
529 Head: head,
530 Indent: r.opt.IndentXML,
531 Prefix: r.opt.PrefixXML,
532 }
533
534 return r.Render(w, x, v)
535 }