package main
import "fmt"
import "net/http"
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "What!")
}
func bar(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Bar!")
}
func main() {
http.HandleFunc("/", home)
http.HandleFunc("/foo", bar)
http.ListenAndServe(":5678", nil)
}
If I visit /foo
, bar
will run.
If I visit /
or /any/other/path
, home
will run.
Any idea why this happens? How can I handle 404's?
This is a behaviour by design - handler defined for path ending with /
will also handle any subpath.
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 == "/".
http://golang.org/pkg/net/http/#ServeMux
You have to implement you own logic for 404. Consider the following example from the golang doc:
mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Welcome to the home page!")
})
You have to handle your own 404s in home
.