何时使用Golang的默认MUX而不是自己编写的MUX?

huangapple go评论67阅读模式
英文:

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

问题

我看到很多帖子都在讨论如何在Go中构建自己的MUX,其中一个例子可以在这里找到(http://thenewstack.io/building-a-web-server-in-go/)。

什么时候应该使用默认的MUX而不是定义自己的MUX?Go文档和这些博客文章都没有说明为什么应该选择其中之一。

英文:

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.

答案1

得分: 29

内置的 mux 有两个缺点:

  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 不是最快的。

考虑到这个基准测试的结论:

首先,没有理由使用 net/http 的默认 ServeMux,它非常有限,性能也不是特别好。有足够多的替代方案,选择你最喜欢的那个。

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

最近,我一直在避免使用默认的 http.Handlehttp.HandleFunc 函数,而是定义一个明确的 http.Handler,然后将其传递给 ListenAndServe(而不是 nil):

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

新的开发者可能会觉得 http.Handlehttp.HandleFunc 之间的区别微妙而令人困惑,所以我认为值得事先了解 http.Handler 的概念。mux 只是另一种类型的 http.Handler(它将请求路由到其他 http.Handler),当你依赖于 DefaultServeMux 时,这个事实被隐藏起来。

英文:

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.

huangapple
  • 本文由 发表于 2015年5月6日 05:22:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/30063442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定