What's the difference between this:
func main() {
http.HandleFunc("/page2", Page2)
http.HandleFunc("/", Index)
http.ListenAndServe(":3000", nil)
}
And using the golang serve mux
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/page2", Page2)
mux.HandleFunc("/", Index)
http.ListenAndServe(":3000", mux)
}
ServerMux
is a type which implements the Handler
interface, all servers have one. In your first example the server just uses the default handler. I don't think there are differences here because the mux returned by NewServeMux
is going to be the same as the default. It is made available so that you can further customize request handling.
Default mux is defined like:
var DefaultServeMux = NewServeMux()
So there's actually no major difference, unless you want to customize further and need an explicit mux for that (for example chain them for some reason).
But since the default is already allocated there's no need to create another one for no reason.
The first program uses the default serve mux. It's identical to the more verbose:
func main() {
http.DefaultServeMux.HandleFunc("/page2", Page2)
http.DefaultServeMux.HandleFunc("/", Index)
http.ListenAndServe(":3000", http.DefaultServeMux)
}
There's one important difference between the two programs: The first program does not have complete control over the handlers used in the program. There are packages that automatically register with the default serve mux from init()
functions (example). If the program imports one of these packages directly or indirectly, the handlers registered by these handlers will be active in the first program.
The second program has complete control over the handlers used with the server. Any handlers registered with the default serve mux are ignored.