| 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 |
|
| 20 |
ContentBinary = "application/octet-stream" |
| 21 |
|
| 22 |
ContentHTML = "text/html" |
| 23 |
|
| 24 |
ContentJSON = "application/json" |
| 25 |
|
| 26 |
ContentJSONP = "application/javascript" |
| 27 |
|
| 28 |
ContentLength = "Content-Length" |
| 29 |
|
| 30 |
ContentText = "text/plain" |
| 31 |
|
| 32 |
ContentType = "Content-Type" |
| 33 |
|
| 34 |
ContentXHTML = "application/xhtml+xml" |
| 35 |
|
| 36 |
ContentXML = "text/xml" |
| 37 |
|
| 38 |
defaultCharset = "UTF-8" |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
type Delims struct { |
| 45 |
|
| 46 |
Left string |
| 47 |
|
| 48 |
Right string |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
type Options struct { |
| 53 |
|
| 54 |
Directory string |
| 55 |
|
| 56 |
FileSystem FileSystem |
| 57 |
|
| 58 |
Asset func(name string) ([]byte, error) |
| 59 |
|
| 60 |
AssetNames func() []string |
| 61 |
|
| 62 |
Layout string |
| 63 |
|
| 64 |
Extensions []string |
| 65 |
|
| 66 |
Funcs []template.FuncMap |
| 67 |
|
| 68 |
Delims Delims |
| 69 |
|
| 70 |
Charset string |
| 71 |
|
| 72 |
DisableCharset bool |
| 73 |
|
| 74 |
IndentJSON bool |
| 75 |
|
| 76 |
IndentXML bool |
| 77 |
|
| 78 |
PrefixJSON []byte |
| 79 |
|
| 80 |
PrefixXML []byte |
| 81 |
|
| 82 |
BinaryContentType string |
| 83 |
|
| 84 |
HTMLContentType string |
| 85 |
|
| 86 |
JSONContentType string |
| 87 |
|
| 88 |
JSONPContentType string |
| 89 |
|
| 90 |
TextContentType string |
| 91 |
|
| 92 |
XMLContentType string |
| 93 |
|
| 94 |
IsDevelopment bool |
| 95 |
|
| 96 |
|
| 97 |
UseMutexLock bool |
| 98 |
|
| 99 |
UnEscapeHTML bool |
| 100 |
|
| 101 |
StreamingJSON bool |
| 102 |
|
| 103 |
RequirePartials bool |
| 104 |
|
| 105 |
RequireBlocks bool |
| 106 |
|
| 107 |
DisableHTTPErrorRendering bool |
| 108 |
|
| 109 |
|
| 110 |
RenderPartialsWithoutPrefix bool |
| 111 |
|
| 112 |
|
| 113 |
BufferPool GenericBufferPool |
| 114 |
} |
| 115 |
|
| 116 |
|
| 117 |
type HTMLOptions struct { |
| 118 |
|
| 119 |
Layout string |
| 120 |
|
| 121 |
Funcs template.FuncMap |
| 122 |
} |
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
type Render struct { |
| 127 |
lock rwLock |
| 128 |
|
| 129 |
|
| 130 |
opt Options |
| 131 |
templates *template.Template |
| 132 |
compiledCharset string |
| 133 |
hasWatcher bool |
| 134 |
} |
| 135 |
|
| 136 |
|
| 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 |
|
| 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) |
| 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 |
|
| 220 |
_ = r.opt.FileSystem.Walk(dir, func(path string, info os.FileInfo, _ error) error { |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 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 |
|
| 253 |
for _, funcs := range r.opt.Funcs { |
| 254 |
tmpl.Funcs(funcs) |
| 255 |
} |
| 256 |
|
| 257 |
|
| 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 |
|
| 317 |
for _, funcs := range r.opt.Funcs { |
| 318 |
tmpl.Funcs(funcs) |
| 319 |
} |
| 320 |
|
| 321 |
|
| 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 |
|
| 333 |
|
| 334 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 435 |
func (r *Render) HTML(w io.Writer, status int, name string, binding interface{}, htmlOpt ...HTMLOptions) error { |
| 436 |
|
| 437 |
r.lock.RLock() |
| 438 |
if r.opt.IsDevelopment && !r.hasWatcher { |
| 439 |
r.lock.RUnlock() |
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
} |