简体   繁体   English

我应该在golang中直接使用ServeMux或http

[英]Should I use ServeMux or http directly in golang

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? 我想知道我是否应该创建一个新的ServeMux并将其注册到http.Server还是应该直接调用http.HandleFunchttp.Handler

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. 我认为使用ServeMux的路由更好,因为http.HandleFunc显然会http.HandleFunc HTTP包的全局状态,这在Go中被认为是不好的做法。 However, in many tutorials, even the official ones, I often see the http.HandleFunc route being used. 但是,在许多教程中,即使是官方教程,我经常会看到正在使用的http.HandleFunc路由。

This makes me wonder: why should one use http.HandleFunc when there is a ServeMux ? 这让我想知道:为什么在有http.HandleFunc时应该使用ServeMux I know that ServeMux has some advantages (eg 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. 我知道ServeMux有一些优点(例如你可以嵌套它而不必一直重复前缀)但我想知道为什么我应该选择http.HandleFunc不是Multiplexer,特别是因为HandleFunc在内部使用ServeMux

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). 编辑:正如评论中所承诺的那样,我已经要求在Golang-dev上弃用额外的(以及无用的IMO函数),他们说没有(好吧,有人说没有)。 Here is the link. 链接在这里。

You're on the right track: you should prefer to instantiate your own ServeMux , for the reasons you've outlined. 你走在正确的轨道上:出于你所概述的原因,你应该更喜欢实例化自己的ServeMux

Using DefaultServeMux also runs the risk of exposing profiling endpoints when using net/http/pprof , since those are attached to the DefaultServeMux. 使用DefaultServeMux时还存在使用net/http/pprof时暴露分析端点的风险,因为它们附加到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. http.Handle|HandleFunc是方便的方法,可能对于保持示例代码中的样板代码很有用,但创建ServeMux使您能够将其包装,将其嵌套在另一个中,从构造函数中导出等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM