Reputation: 496
I recently asked about serving static content and handling 404 with Gorilla mux; when using Handle instead of PathPrefix, the app can serve the root page (http://localhost:8888):
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.Handle("/", http.FileServer(http.Dir("./static")))
r.NotFoundHandler = http.HandlerFunc(notFound)
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
However requests for pages within the root page (e.g. http://localhost:8888/demo/page1.html) get intercepted by the 404 handler. Is there any way to prevent this, while catching requests for non-existent pages or services? This is the directory structure:
...
main.go
static\
| index.html
demo\
page1.html
demo.js
demo.css
| jquery\
| <js files>
| images\
| <png files>
Previous Question:
I am using the Gorilla mux toolkit to handle http requests in a web server app:
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
I want to add a handler for invalid URLS, but it is never called:
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
If I remove the static handler, the not found handler is called. However, the app needs to serve the static content, from a non-absolute path. Is there a way to combine that with 404 handling?
Upvotes: 2
Views: 2012
Reputation: 1323183
I suspect r.PathPrefix("/").Handler()
would match any path, making the notfound
handler useless.
As mentioned in "route.go
":
// Note that it does not treat slashes specially
// ("`/foobar/`" will be matched by the prefix "`/foo`")
// so you may want to use a trailing slash here.
If you are using PathPrefix
(as in those tests), use it for a specific path, not for the generic "/
".
Upvotes: 1