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

标签 http go mux

<分区>

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

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

最佳答案

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

  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.Handle 的方向前进和 http.HandleFunc函数并定义显式 http.Handler相反,然后将其交给ListenAndServe . (而不是 nil :

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

新手开发者发现 http.Handle 之间的区别和 http.HandleFunc微妙且令人困惑,所以我认为值得理解 http.Handler前面的概念。多路复用器只是另一种 http.Handler (将请求路由到其他 http.Handler 的一个)当您依赖 DefaultServeMux 时,现实就被隐藏起来了.

关于http - 何时使用 Golang 的默认 MUX 与使用自己的 MUX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30063442/

相关文章:

go - slice : Out of bounds error in Go

http - 动态路由的文件服务器目录

internet-explorer - 在 Internet Explorer 中看到 "Web page has expired"的 HTTP 响应代码是什么?

http - 缓存控制: max-age affected by intermediate caching?如何

php - 重定向跳过 www 是常见的做法吗?

php - 是否可以在 PowerMTA 上阅读收到的电子邮件?

xml - 去: Unmarshall XML List containing different entities

戈朗 : can't decompress data with lzw package

postgresql - 使用 SQLX 转到可选字段

rest - 如何将参数传递给MiddlewareFunc?