I've created nested templating that works when I use "net/http" and http.HandelFunc , however, I've decided to use "github.com/julienschmidt/httprouter" going forward as I want to have move flexibility and now my templates don't work, I get a 404 error.
Please, can you help?
Directory structure
/
/main.go
/templates
/templates/tstats/file.go.html
This code works
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)
}
The new code that is producing a 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)
}
Revising after the comment response. I had a look https://play.golang.org/p/iHUqZQQcv3
You have following issues:
r.GET("/tstats/", serveTemplate)
- It will only match http://localhost:8080/tstats/
rest everything is 404
http://localhost:8080/tstats/myfile1.html
filepath.Join("templates", filepath.Clean(r.URL.Path))
Honestly it is very hard to guess, how you're planning/designing your application. Anyway-
Update your code like below:
/tstats/
=> /tstats/*tmpl
in the router mappingfp := filepath.Join("templates", filepath.Clean(r.URL.Path))
=> fp := filepath.Join("templates", "tstats", params.ByName("tmpl"))
Now, for the request http://localhost:8080/tstats/myfile1.html. It will look for template here templates/tstats/myfile1.html
.
(This was initial response)
It seems like HandlerFunc
register issue that leading to 404.
I have created sample from your code, can you try https://play.golang.org/p/6ilS0htj-I
BTW, I believe; in your first sample code tpl
variable in the func init
is not used. Since you have local variable of same name in the serveTemplate
.