When to use Golang's default MUX versus doing your own [closed]
Asked Answered
A

1

16

I have seen a lot of posts talk about building your own MUX in Go, one of the many examples is here (http://thenewstack.io/building-a-web-server-in-go/).

When should you use the default versus defining your own? The Go docs and none of the blog posts say why you should use one over the other.

Annotate answered 5/5, 2015 at 21:22 Comment(2)
There are a LOT of routers/muxes out there for Go. The built-in net/http one is functional, and ones like gorilla/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
So much agreement re: "Routers are only a small slice of the response-time pie." Get something working whatever way is easiest first.Carnotite
O
30

There are two downsides to the builtin mux:

  1. 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.

  2. 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.Handlers) and that reality is hidden away when you rely on the DefaultServeMux.

Ovotestis answered 5/5, 2015 at 21:53 Comment(1)
There is no 'SplitN' method on req.URL.Path. Rather use: strings.SplitN(...Artimas

© 2022 - 2024 — McMap. All rights reserved.