dongyao2001 2019-07-27 13:46
浏览 82
已采纳

映射中存储的HTML模板在首次调用时崩溃

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.

  • 写回答

1条回答 默认 最新

  • douyue8191 2019-07-27 14:12
    关注

    The problem is that t is undefined, due to variable shadowing:

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

    Within your if block, you're re-defining t with t := .... This means you have a new, locally-scoped t, and once you leave the if block, you still have the outer t which is still `nils.

    Change the marked line to:

        t = template.New(name)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集