4

我想创建一个将调用布尔函数的应用程序,并根据结果提供 2 个已编译的反应应用程序中的 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 返回为真时,它应该在站点/新加载静态内容,否则加载站点/旧。

但是加载 glob 会产生: panic: read sites/new/static: is a directory 开始恐慌时。

单独加载 html 文件(上面注释掉)运行良好,但是当请求到来时它会出现以下情况:

html/template: "new/index.html" is undefined

我还在 c.HTML 中使用了 sites/[old||new]/index.html 字符串

4

2 回答 2

2

尝试sites/**/*.html解决恐慌。

请注意,Go 使用模板文件的基本名称作为模板名称,因此要执行您不使用"path/to/template.html""template.html". 当然,这会导致您的情况出现问题,因为如文档中所述:

当解析不同目录中的多个同名文件时,最后提到的将是结果。

要解决此问题,您需要显式命名您的模板,您可以使用该操作来执行此{{ define "template_name" }}操作。

  1. 打开sites/new/index.html
  2. 添加{{ define "new/index.html" }}为第一行
  3. 添加{{ end }}为最后一行
  4. sites/old/index.html以with"old/index.html"作为名称重复。
于 2019-04-25T14:55:00.283 回答
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 }}
于 2019-04-25T14:51:32.867 回答