mycellius
mycellius

Reputation: 598

Using HandleFunc on http vs mux

I'm new to go and want to set up some routing, as well as cors. I've been seeing two styles of doing so, one that initializes a multiplexer with NewServeMux and then assigns handlers with HandleFunc, and one that uses HandleFunc directly on http. This is what I mean:

mux := http.NewServeMux()
mux.HandleFunc("/api", apiFunc)
mux.HandleFunc("/", indexFunc)

vs

http.HandleFunc("/api", apiFunc)
http.HandleFunc("/", indexFunc)
http.ListenAndServe("127.0.0.1:3001", nil)

Are there any differences with these approaches? If they accomplish similar things, is one more common/pragmatic?

Upvotes: 9

Views: 4054

Answers (2)

Marcin Kulik
Marcin Kulik

Reputation: 983

http.HandleFunc() uses DefaultServeMux which is a global variable. Therefore any third party package can have access to DefaultServeMux. In a scenario in which a third party package was compromised, it could use DefaultServeMux to expose malicious handler to your web application. This is one of the reasons why it is recommended in production code to use your own servemux as shown in your first example.

Upvotes: 5

Adrian
Adrian

Reputation: 46552

http.HandleFunc et al apply your handlers to a package-global instance of the ServeMux held in the http package, which http.ListenAndServe then starts. You can also create your own instance as you did in the first example, which gives you some more control and makes it easier to unit test. In the end, the choice is yours; the convenience functions and package globals are probably fine for smaller projects with a limited maintenance period, but for larger or longer-lived projects I would generally recommend managing your own instances of both ServeMux and Server.

Upvotes: 4

Related Questions