I am using the function below to parse and save a Go template to a map the first time the template is invoked.
Subsequently, the template is loaded from the map for optimization.
// Resource ...
type Resource struct {
Templates map[string]template.Template
}
func (res *Resource) FetchTemplate(templateName string) (template.Template, bool) {
tmpl, ok := res.Templates[templateName]
return tmpl, ok
}
func (res *Resource) ExecTemplate(w http.ResponseWriter, name, path string, model interface{}) error {
t, ok := res.FetchTemplate(name)
if !ok{
t := template.New(name)
t, err := t.ParseFiles(res.Assets + path)
t = template.Must(t, err)
if err != nil {
return err
}
res.Templates[name] = *t
}
if err := t.Execute(w, model); err != nil {
w.WriteHeader(http.StatusBadGateway)
return err
}
return nil
}
The first time the code is invoked on a template however, it panics on the t.Execute
call.
It always works subsequently.
Here are the error logs.
/usr/local/go/src/net/http/server.go:1746 +0xd0
panic(0x15b3ac0, 0x1b1c8d0)
/usr/local/go/src/runtime/panic.go:513 +0x1b9
html/template.(*Template).escape(0xc000127088, 0x0, 0x0)
/usr/local/go/src/html/template/template.go:95 +0x32
html/template.(*Template).Execute(0xc000127088, 0x4a90200, 0xc000374680, 0x15ed6c0, 0xc000370a20, 0x0, 0x0)
/usr/local/go/src/html/template/template.go:119 +0x2f
git.imaxinacion.net/uoe/anssid/app/resource.(*Resource).ExecTemplate(0xc0002ee120, 0x4a901b0, 0xc000374680, 0x16577a3, 0x5, 0x1660b7a, 0x10, 0x15ed6c0, 0xc000370a20, 0x145de5e, ...)
/Users/gbemirojiboye/go/src/git.imaxinacion.net/uoe/anssid/app/resource/resource.go:110 +0x1ef
What could be the cause of this?
When I was creating a new template for each call, this was not happening.