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) }
ServeMux is an HTTP request multiplexer. It is used for request routing and dispatching. The request routing is based on URL patterns. Each incoming request's URL is matched against a list of registered patterns. A handler for the pattern that most closely fits the URL is called.
In go ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.
The Handler interface is an interface with a single method ServeHTTP which takes a http. Response and a http. Request as inputs. This method can be said as the core method which “responds” to a given http request .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With