何时使用 Golang 的默认 MUX 与使用自己的 MUX

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

我看过很多关于在 Go 中构建自己的 MUX 的帖子,这里是众多示例之一 (http://thenewstack.io/building-a-web-server-in-go/)。

什么时候应该使用默认值而不是自己定义? Go 文档和博客文章的 none 说明了为什么您应该使用一个而不是另一个。

内置多路复用器有两个缺点:

  1. 如果您需要来自 url 的信息(例如 /users/:id 中的 id),您必须手动完成:

    http.HandleFunc("/users/", func(res http.ResponseWriter, req *http.Request) {
        id := strings.SplitN(req.URL.Path, "/", 3)[2]
    })
    

    比较麻烦

  2. 默认服务器 mux 不是最快的。

考虑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.

所以它唯一的优点是每个人都已经拥有它,因为它包含在 net/http

最近我一直在朝着避免默认 http.Handlehttp.HandleFunc 函数的方向发展,而是定义一个明确的 http.Handler ,然后交给 ListenAndServe. (而不是 nil:

handler := http.NewServeMux()
handler.Handle("/whatever", ...)
http.ListenAndServe(80, handler)

新手开发人员发现 http.Handlehttp.HandleFunc 之间的区别微妙且令人困惑,因此我认为有必要预先了解 http.Handler 概念。多路复用器只是另一种 http.Handler(将请求路由到其他 http.Handler),当您依赖 DefaultServeMux.

时,现实就被隐藏起来了