Html 存储在地图中的模板在第一次调用时崩溃

Html template stored in map crashes on first invocation

我正在使用下面的函数在第一次调用模板时解析 Go 模板并将其保存到地图。

随后从地图中加载模板进行优化。

// 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
}

然而,第一次在模板上调用代码时,它会在 t.Execute 调用时出现混乱。

它总是随后起作用。

这是错误日志。

  /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

这可能是什么原因?

当我为每个调用创建新模板时,并没有发生这种情况。

问题是 t 未定义,由于变量遮蔽:

t, ok := res.FetchTemplate(name)
if !ok{
    t := template.New(name) // <---- The problem is here
    t, err := t.ParseFiles(res.Assets + path)

在您的 if 块中,您正在用 t := ... 重新定义 t。这意味着你有一个新的、局部范围的 t,一旦你离开 if 块,你仍然有外部 t,它仍然是 `nils.

将标记行更改为:

    t = template.New(name)