预缓存Golang模板或更有效的方法

预缓存Golang模板或更有效的方法,go,go-templates,Go,Go Templates,我有一个web应用程序,我正在尝试按照如下建议预缓存我的模板: 目前这就是我正在做的。(我提供了示例模板帮助器函数来帮助您了解情况) (注意,App对象是App的其余部分,处理实际的web服务和DB内容) } func(app*app)defaultTempleHelpers(w http.ResponseWriter,r*http.Request)template.FuncMap{ m:=template.FuncMap{ “sessionfoo”:func()bool{ //某些功能 返回

我有一个web应用程序,我正在尝试按照如下建议预缓存我的模板:

目前这就是我正在做的。(我提供了示例模板帮助器函数来帮助您了解情况) (注意,App对象是App的其余部分,处理实际的web服务和DB内容)

}

func(app*app)defaultTempleHelpers(w http.ResponseWriter,r*http.Request)template.FuncMap{
m:=template.FuncMap{
“sessionfoo”:func()bool{
//某些功能
返回hasUserSession(r)
},
“酒吧”:进行辩论的功能,
}
/*
更多的模板函数
*/
返回m
}
func myPageWithLayout(app*app,w http.ResponseWriter,r*http.Request,路径字符串,文件字符串,布局字符串,funcs template.FuncMap,数据映射[string]接口{}){
logger.Debugf(“在路径%+v处使用布局%+v的呈现模板,第%+v页”,布局,路径,文件)
t、 错误:=template.New(file).Funcs(Funcs).ParseFiles(
Join(templatesPath、path、file),
Join(templatesPath,“layouts”,layout),
)
如果错误!=零{
logger.Errorf(“错误呈现html模板%+v:%+v”,文件,err.error())
http.Error(w,“Error”,http.StatusInternalServerError)
返回
}
//以前用于建立默认模板数据
templData:=map[string]接口{}{}
//将传入的数据与模板数据合并
对于k,v:=范围数据{
模板数据[k]=v
}
executeTemplate(w、t、TemplateData)
}
///以下是模板示例:
/*
apagewithfuncs.html:
你好
{{functiontakingarguments“astring”“asecondstring”}
{{if sessionfoo}}与会话函数{{{else}}无关!{{end}
*/
我打赌,你可以很容易地在这里发现第一组问题。对于每个请求,每次都必须从磁盘读取模板

因为我有一些模板函数依赖于用户查看它们的内容或会话变量,所以我将r*http.Request传递到模板呈现函数中,以便在调用我的助手函数时,它们可以访问该请求数据

就我所知,这意味着我不能像前面的链接()中描述的那样准确地预缓存这些模板

那么,首先,一般来说,这是一种不好的方法吗?(并非推卸责任,但其中一些代码来自另一个程序员)

第二,有没有办法提高效率?比如,缓存其中的某些部分,但仍然能够使用这些助手函数?
我很确定整个设置都在拖我的应用程序性能的后腿,但我可能错了。我曾经尝试过一些丑陋的方法,比如尝试(一些参数…接口{}),然后键入casting(是的,我是一个可怕的罪人)

将每个请求的所有状态作为参数传递给执行。 定义封装每个请求状态的类型:

type data struct {
   r *http.Request
   Data map[string]interface{}
}

func (d *data) SessionFoo() bool {
    return hasUserSession(d.r)
}
在模板中使用该类型:

<h1> Hello! </h1>
{{ functiontakingarguments "astring" "asecondstring" }}

{{ if $.SessionFoo }} Something to do with that session function {{else}} nevermind! {{end}}

templData["x"] is {{$.Data.x}}

是的,我必须重写实际调用模板的Execute的函数,我需要编写一种方法来检索正确的预缓存模板(因为我不会每次都重新创建它们,并且计划缓存单个模板,而不是将每个模板缓存成一个大模板),这看起来是正确的路径(还有路上的大部分台阶)!
type data struct {
   r *http.Request
   Data map[string]interface{}
}

func (d *data) SessionFoo() bool {
    return hasUserSession(d.r)
}
<h1> Hello! </h1>
{{ functiontakingarguments "astring" "asecondstring" }}

{{ if $.SessionFoo }} Something to do with that session function {{else}} nevermind! {{end}}

templData["x"] is {{$.Data.x}}
err := myPageTemplate.Execute(w, data{Data:templData, r:r})
if err != nil {
   // handle error
}