golang模板不适用于httprouter

golang模板不适用于httprouter,go,nested,go-templates,Go,Nested,Go Templates,我已经创建了嵌套模板,当我使用“net/http”和http.HandelFunc时可以工作,但是,我决定继续使用“github.com/julienschmidt/httprouter”,因为我希望有移动灵活性,现在我的模板不工作了,我得到了一个404错误 拜托,你能帮忙吗 目录结构 / /main.go /templates /templates/tstats/file.go.html 此代码有效 func init() { tpl = template.Must(template

我已经创建了嵌套模板,当我使用“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)
   }

在评论回复后修改。我看了一眼

您有以下问题:

  • 路由器处理程序寄存器问题
    r.GET(“/tstats/”,serveTemplate)
    -它将只匹配
    http://localhost:8080/tstats/
    rest一切正常
    404
    • 例如:404->
      http://localhost:8080/tstats/myfile1.html
  • 计算模板路径文件
    filepath.Join(“模板”,filepath.Clean(r.URL.path))
  • 老实说,很难猜测您是如何规划/设计应用程序的。反正-

    更新您的代码,如下所示:

    • 在路由器映射中更改
      /tstats/
      =>
      /tstats/*tmpl
    • 更改
      fp:=filepath.Join(“模板”,filepath.Clean(r.URL.Path))
      =>
      fp:=filepath.Join(“模板”,“tstats”,参数.ByName(“tmpl”)
    现在,请求。它将在这里查找模板
    templates/tstats/myfile1.html


    (这是最初的反应)

    似乎是
    HandlerFunc
    寄存器问题导致了404

    我已经从你的代码中创建了示例,你能试试吗


    顺便说一句,我相信;在第一个示例代码中,
    tpl
    未使用
    func init
    中的变量。既然您在
    serveTemplate

    中有同名的局部变量,我希望您的意思是
    http.HandleFunc
    ,而不是。嘿,谢谢您的回答,我只使用了Go大约4周,非常新。我尝试了你的解决方案,但仍然得到相同的404错误。对于404,这肯定是你的路由器分配/创建问题。你能把你的代码放在play.golang.org上分享吗?我去看看。嘿,它在这儿。我一直在玩它,所以我评论了一些东西。