Should I use ServeMux or http directly in golang

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

Should I use ServeMux or http directly in golang

问题

我在思考是否应该创建一个新的ServeMux并将其注册到http.Server,还是直接调用http.HandleFunchttp.Handler

我认为使用ServeMux路由更好,因为http.HandleFunc明显会干扰HTTP包的全局状态,这在Go语言中被认为是不好的实践。然而,在许多教程中,甚至是官方教程中,我经常看到使用http.HandleFunc的路由。

这让我想知道:为什么有了ServeMux还要使用http.HandleFunc呢?我知道ServeMux有一些优点(例如,可以嵌套使用而无需一直重复前缀),但我想知道为什么我应该选择http.HandleFunc而不是Multiplexer,特别是因为HandleFunc在内部使用了ServeMux。

编辑:如我在评论中承诺的那样,我已经在Golang-dev上要求废弃了额外的(我认为是无用的)函数,但他们拒绝了(至少有一个人拒绝了)。这是链接。

英文:

I was wondering if I should create a new ServeMux and register it to the http.Server or should I invoke http.HandleFunc and http.Handler directly?

I think the route with a ServeMux is better because http.HandleFunc obviously messes with the global state of the HTTP package, which is considered bad practice in Go. However, in many tutorials, even the official ones, I often see the http.HandleFunc route being used.

This makes me wonder: why should one use http.HandleFunc when there is a ServeMux? I know that ServeMux has some advantages (e.g. you can nest it without repeating the prefix all the time) but I wonder why I should ever choose http.HandleFunc over Multiplexer, especially since HandleFunc uses a ServeMux internally.

Edit: as promised in the comments, I've asked to deprecate the additional (and useless IMO functions) on Golang-dev and they said no (well, on person said no). Here is the link.

答案1

得分: 10

你走在正确的道路上:你应该优先实例化自己的ServeMux,原因如你所述。

使用DefaultServeMux还存在一个风险,即在使用net/http/pprof时,可能会暴露性能分析的端点,因为这些端点附加在DefaultServeMux上。

http.Handle|HandleFunc是方便的方法,也许在示例代码中可以减少样板代码,但是创建一个ServeMux可以让你对其进行包装、嵌套在另一个ServeMux中、从构造函数中导出等等。

英文:

You're on the right track: you should prefer to instantiate your own ServeMux, for the reasons you've outlined.

Using DefaultServeMux also runs the risk of exposing profiling endpoints when using net/http/pprof, since those are attached to the DefaultServeMux.

http.Handle|HandleFunc are convenience methods, and perhaps useful for keeping the boilerplate in example code down, but creating a ServeMux gives you the ability to wrap it, nest it within another, export it from a constructor, etc.

huangapple
  • 本文由 发表于 2016年3月27日 23:12:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/36248946.html
匿名

发表评论

匿名网友

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

确定