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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!