golang 模板不适用于 httprouter

golang templates not working with httprouter

我创建了嵌套模板,当我使用 "net/http" 和 http.HandelFunc 时可以使用,但是,我决定继续使用 "github.com/julienschmidt/httprouter" 因为我想要移动灵活性现在我的模板不起作用,出现 404 错误。

拜托,你能帮忙吗?

目录结构

/
/main.go
/templates
/templates/tstats/file.go.html

此代码有效

func init() {
    tpl = template.Must(template.ParseGlob("templates/*.go.html"))
}
http.HandleFunc("/tstats/", serveTemplate)

func serveTemplate(w http.ResponseWriter, r *http.Request) {
    lp := filepath.Join("templates", "layout.html")
    fp := filepath.Join("templates", filepath.Clean(r.URL.Path))
    gh := filepath.Join("templates", "INC_Header.go.html")
    gn := filepath.Join("templates", "INC_Nav.go.html")
    gf := filepath.Join("templates", "INC_Footer.go.html")
    //log.Println(r.URL.Path)

tpl, err := template.ParseFiles(lp, fp, gh, gn, gf)
if err := tpl.ExecuteTemplate(w, "layout", nil); err != nil {
    log.Println(err.Error())
    http.Error(w, http.StatusText(500), 500)
}

产生 404 的新代码

func serveTemplate(w http.ResponseWriter, r *http.Request, _ 
    httprouter.Params) {
    lp := filepath.Join("templates", "layout.html")
    fp := filepath.Join("templates", filepath.Clean(r.URL.Path))
    gh := filepath.Join("templates", "INC_Header.go.html")
    gn := filepath.Join("templates", "INC_Nav.go.html")
    gf := filepath.Join("templates", "INC_Footer.go.html")
    //log.Println(`enter code here`r.URL.Path)

    tmpl, err := template.ParseFiles(lp, fp, gh, gn, gf)
    if err := tmpl.ExecuteTemplate(w, "layout", nil); err != nil {
        log.Println(err.Error())
        http.Error(w, http.StatusText(500), 500)
   }

评论回复后修改。我看了https://play.golang.org/p/iHUqZQQcv3

您有以下问题:

  1. 路由器处理程序注册问题 r.GET("/tstats/", serveTemplate) - 它只会匹配 http://localhost:8080/tstats/ 其余一切都是 404
    • 例如:404 -> http://localhost:8080/tstats/myfile1.html
  2. 你计算模板路径文件的方式filepath.Join("templates", filepath.Clean(r.URL.Path))

老实说,很难猜到您 planning/designing 您的申请情况如何。不管怎样-

像下面这样更新您的代码:

  • 在路由器映射中更改/tstats/ => /tstats/*tmpl
  • 更改fp := filepath.Join("templates", filepath.Clean(r.URL.Path)) => fp := filepath.Join("templates", "tstats", params.ByName("tmpl"))

现在,对于请求 http://localhost:8080/tstats/myfile1.html。它会在这里寻找模板 templates/tstats/myfile1.html.


(这是初始回复)

似乎 HandlerFunc 导致 404 的注册问题。

我已经根据你的代码创建了示例,你可以试试吗https://play.golang.org/p/6ilS0htj-I

顺便说一句,我相信;在你的第一个示例代码中 tpl 变量中的 func init 没有被使用。由于您在 serveTemplate.

中有同名的局部变量