Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

go

mux

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.

like image 297
jordan2175 Avatar asked May 05 '15 21:05

jordan2175


People also ask

Why is gorilla mux used?

Gorilla Mux provides functionalities for matching routes, serving static files, building single-page applications (SPAs), middleware, handling CORS requests, and testing handlers. This tutorial will walk you through using the Gorilla Mux package as a router for your applications.

What is a HTTP mux?

HTTP multiplexing is the re-use of established server connections for multiple clients connections. The best way to understand this feature is to compare non-multiplexing behavior to multiplexing behavior.

How does Gorilla mux work?

Package gorilla/mux implements a request router and dispatcher for matching incoming requests to their respective handler. The name mux stands for "HTTP request multiplexer". Like the standard http.

Which method from net HTTP package will create a new server and start listening at given address?

ListenAndServe function to start the server and tell it to listen for new HTTP requests and then serve them using the handler functions you set up.


1 Answers

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.

like image 113
Caleb Avatar answered Sep 20 '22 19:09

Caleb