golang 模板不适用于 httprouter

标签 go nested go-templates

我已经创建了嵌套模板,当我使用“net/http”和 http.HandelFunc 时它可以工作,但是,我决定继续使用“github.com/julienschmidt/httprouter”,因为我想要移动灵 active 现在我的模板不起作用,出现 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))

老实说,很难猜测您是如何规划/设计您的应用程序的。无论如何-

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

  • 更改路由器映射中的/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

顺便说一句,我相信;在您的第一个示例代码中,未使用 func init 中的 tpl 变量。因为您在 serveTemplate 中有同名的局部变量。

关于golang 模板不适用于 httprouter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536284/

相关文章:

performance - go 中的 map vs switch 性能

google-app-engine - Goapp 服务 - 警告 : There are too many files

c++ - 如何覆盖继承的嵌套类中存在的虚方法

go - 图源 "invalid memory address ... "with http.client

if-statement - 其他人真的是代码味道吗?编写 Go 条件的惯用方式

excel - Excel 中的 if 或嵌套循环过多

javascript - 如何推送到嵌套在对象中的数组?

go - Gcloud函数部署找不到Golang模板文件

go - 将数组的索引传递给模板

kubernetes - 在Helm configMap中包含文件内容后如何控制缩进?