我想创建一个将调用布尔函数的应用程序,并根据结果提供2个已编译的React应用程序中的1个作为静态站点。
我正在使用gin推荐的LoadHTMLGlob函数,它可以与.tmpl文件一起正常工作,如其文档中的示例。但是,当只为每个站点创建带有静态目录的静态html时,一切似乎进展顺利。
文件结构:
├── main.go
└── sites
├── new
│ ├── index.html
│ └── static
└── old
├── index.html
└── static
执行代码:
func main() {
r := gin.Default()
//r.LoadHTMLFiles("sites/old/index.html", "sites/new/index.html") //doesn't complain, but can't load html
r.LoadHTMLGlob("sites/**/*") // complains about /static being a dir on boot
r.GET("/sites/lib", func(c *gin.Context) {
id := c.Query("id")
useNewSite, err := isBetaUser(id)
if err != nil {
c.AbortWithStatusJSON(500, err.Error())
return
}
if useNewSite {
c.HTML(http.StatusOK, "new/index.html", nil)
} else {
c.HTML(http.StatusOK, "old/index.html", nil)
}
})
routerErr := r.Run(":8080")
if routerErr != nil {
panic(routerErr.Error())
}
}
我希望当isBetaUser恢复为true时,应该将静态内容加载到site / new下,否则将加载site / old。
但是,加载glob会产生:
panic: read sites/new/static: is a directory
开始恐慌时。
分别加载html文件(上面已注释) 运行正常,但是当请求到来时会出现以下情况:
html/template: "new/index.html" is undefined
我还使用c.HTML中的sites / [old || new] /index.html进行了字符串
答案 0 :(得分:2)
尝试sites/**/*.html
纠正恐慌。
请注意,Go使用模板文件的 base 名称作为模板名称,因此要执行模板,您不需要使用"path/to/template.html"
,而是使用"template.html"
。当然,这会引起您的问题,因为documentation中已经说明了:
以不同的名称解析具有相同名称的多个文件时 目录,最后提到的将是结果目录。
要解决此问题,您需要使用{{ define "template_name" }}
操作明确命名模板。
sites/new/index.html
{{ define "new/index.html" }}
作为第一行{{ end }}
作为最后一行sites/old/index.html
为名称重复"old/index.html"
。答案 1 :(得分:0)
您首先需要在模板文件中定义模板,无论它是html / tmpl文件。
{{ define "new/index.tmpl" }} ... {{ end }}
或者,如果您要坚持使用html文件,那么应该是
{{ define "new/index.html" }} ... {{ end }}
。
因此,您的模板文件(来自您的示例:sites/new/index.html
)应如下所示,
{{ define "new/index.html" }}
<html>
<h1>
{{ .title }}
</h1>
<p>New site</p>
</html>
{{ end }}