gpt4 book ai didi

golang 模板不适用于 httprouter

转载 作者:数据小太阳 更新时间:2023-10-29 03:24:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com