There are two downsides to the builtin mux:
If you need info from the url (for example id in /users/:id
) you have to do it manually:
http.HandleFunc("/users/", func(res http.ResponseWriter, req *http.Request) {
id := strings.SplitN(req.URL.Path, "/", 3)[2]
})
Which is cumbersome.
The default server mux is not the fastest.
Consider the conclusions from this benchmark:
First of all, there is no reason to use net/http's default ServeMux, which is very limited and does not have especially good performance. There are enough alternatives coming in every flavor, choose the one you like best.
So really its only advantage is that everyone already has it since it's included in net/http
.
Lately I've been moving in the direction of avoiding the default http.Handle
and http.HandleFunc
functions and defining an explicit http.Handler
instead, which is then handed to ListenAndServe
. (instead of nil
:
handler := http.NewServeMux()
handler.Handle("/whatever", ...)
http.ListenAndServe(80, handler)
Newer developers find the distinction between http.Handle
and http.HandleFunc
subtle and confusing so I think it's worth understanding the http.Handler
concept up front. A mux is just another kind of http.Handler
(one that routes requests to other http.Handler
s) and that reality is hidden away when you rely on the DefaultServeMux
.
net/http
one is functional, and ones likegorilla/mux
have a significant number of features you can choose from.httprouter
sits down the end at the slim end. I would think that the need to write your own—if you have to ask the question—would almost (but never say never!) not exist. Routers are only a small slice of the response-time pie. – Schedule