I've been studying golang and I noticed a lot of people create servers by using the http.NewServeMux() function and I don't really understand what it does.
I read this:
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.
How is that different than just doing something like:
http.ListenAndServe(addr, nil)
http.Handle("/home", home)
http.Handle("/login", login)
What is the purpose of using multiplexing?
From
net/httpGoDoc and Source.ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMuxDefaultServeMuxis just a predefinedhttp.ServeMuxAs you can see
http.HandlecallsDefaultServeMuxinternally.func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }The purpose of
http.NewServeMux()is to have your own instance ofhttp.ServerMuxfor instances like when you require twohttp.ListenAndServefunctions listening to different ports with different routes.