The URL pattern to which you register your handlers is documented in the http.ServeMux
type:
Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.
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 == "/".
So unfortunately there is no pattern which matches only the root ("/"
).
But you can easily check this in your handler, and do whatever you want to if the request path is not the root:
func serveRest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.Write([]byte("Not root!"))
return
}
w.Write([]byte("Hi, this is the root!"))
}
If you want to return HTTP 404 Not found
error for non-roots:
func serveRest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Write([]byte("Hi!"))
}
And Go tutorial: https://tour.golang.org/
Also check out the <kbd>Go</kbd> tag info here on SO, it has a section Go Tutorials.