I have these routes:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
renderAndExecuteTemplate(w, r, "page/index.tmpl", nil)
})
http.HandleFunc("/route1", func(w http.ResponseWriter, r *http.Request) {
renderAndExecuteTemplate(w, r, "page/route1.tmpl", nil)
})
http.HandleFunc("/route2", func(w http.ResponseWriter, r *http.Request) {
renderAndExecuteTemplate(w, r, "page/route2.tmpl", nil)
})
It works.
However, when I go to a route which doesn't exist: "localhost/fdsafdsafdsfds", it still renders the "index" page.
Why? How to prevent it from that?
From the docs:
Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".
One way to prevent this is to build a handler that looks at the request:
http.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
renderAndExecuteTemplate(w, r, "page/index.tmpl", nil)
})