Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between http and default servemux?

Tags:

go

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) } 
like image 958
DangMan Avatar asked Apr 28 '16 17:04

DangMan


People also ask

What is a ServeMux?

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.

What is HTTP request multiplexer?

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.

What are HTTP handlers in Golang?

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 .


1 Answers

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.

like image 173
Bayta Darell Avatar answered Sep 28 '22 04:09

Bayta Darell