Optimizing template cache by using an application config ***
This commit is contained in:
@ -2,29 +2,40 @@ package render
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"go-udemy-web-1/pkg/config"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
var app *config.AppConfig
|
||||
|
||||
// NewTemplates sets the config for the template package
|
||||
func NewTemplates(a *config.AppConfig) {
|
||||
app = a
|
||||
}
|
||||
|
||||
// RenderTemplate renders a HTML template file
|
||||
func RenderTemplate(w http.ResponseWriter, tmpl string) {
|
||||
// create a template cache
|
||||
tc, err := createTemplateCache()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
var tc map[string]*template.Template
|
||||
if app.UseCache {
|
||||
// get the template cache from the app config
|
||||
tc = app.TemplateCahce
|
||||
} else {
|
||||
tc, _ = CreateTemplateCache()
|
||||
}
|
||||
|
||||
// get requested template from cache
|
||||
t, ok := tc[tmpl]
|
||||
if !ok {
|
||||
log.Fatal(err)
|
||||
log.Fatal("Could not get template from template cache")
|
||||
}
|
||||
|
||||
// Write to a buffer to make sure that the template can be read and
|
||||
// written successfully
|
||||
buf := new(bytes.Buffer)
|
||||
err = t.Execute(buf, nil)
|
||||
err := t.Execute(buf, nil)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
@ -36,7 +47,7 @@ func RenderTemplate(w http.ResponseWriter, tmpl string) {
|
||||
}
|
||||
}
|
||||
|
||||
func createTemplateCache() (map[string]*template.Template, error) {
|
||||
func CreateTemplateCache() (map[string]*template.Template, error) {
|
||||
myCache := map[string]*template.Template{}
|
||||
|
||||
// get all of the files named *.page.tmpl from ./templates
|
||||
|
Reference in New Issue
Block a user