我創建了嵌套的模板,當我使用「net/http」和http.HandelFunc時,但是,我決定使用「github.com/julienschmidt/httprouter」我想要有靈活性,現在我的模板不起作用,我收到了404錯誤。golang模板不能使用httprouter
請問,你能幫忙嗎?
目錄結構
/
/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)
}
我希望你的意思是'http.HandleFunc',而不是['http.HandelFunc'](https://www.youtube.com/watch?V = 71NCzuDNUcg)。 – Flimzy