@techjanitor @420303865 这是一个棘手的问题。我不记得为什么将 context.Engine 设置为导出变量。
@techjanitor,你的代码可能看起来不错,但这太不安全了。您正在修改请求内的全局变量。如果您的应用程序配置为GOMAXPROCS
> 0,则:
tmpl := template.Must(template.ParseFiles("main.tmpl", "index.tmpl"))
c.Engine.HTMLRender = render.HTMLRender{
Template: tmpl,
}
// <<< here another request in a different thread could modify c.Engine.HTMLRender
// even worse, two threads could modify the variable at the same time. and you get a race condition.
c.HTML(200, "base", m.Result)
router.HTMLRender 应在开始时初始化,否则应c.Render
直接使用。
// c.Render is stateless, so it is thread-safe
c.Render(200, render.HTML{
Template: template.Must(template.ParseFiles("main.tmpl", "index.tmpl")),
Name: "main.templ",
Data: yourData,
})
或者直接使用模板:
tmpl := template.Must(template.ParseFiles("main.tmpl", "index.tmpl"))
c.Header("Content-Type", "text/html; charset=utf-8")
c.Writer.WriteHeader(200)
tmpl.ExecuteTemplate(c.Writer, "main.tmpl", yourData)