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

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真