我应该在http.ListenAndServe中使用goroutines吗?

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

Should I be using goroutines with http.ListenAndServe?

问题

如果我使用http.ListenAndServe来提供用户访问URL时的响应,我应该将相应的操作作为goroutine在函数中触发吗?

例如,假设我在监听/

func main() {
    http.HandleFunc("/", provideMainContent)
}

func provideMainContent(w http.ResponseWriter, r *http.Request) {
    // 一堆代码,从数据库中查找详细信息,解析,然后返回
}

provideMainContent中的一堆代码是否应该包装在goroutine中,以免拖慢之后可能到来的请求?

英文:

If I'm using http.ListenAndServe to provide responses when the user hits a URL, should I be firing off the corresponding actions in the function as a goroutine ?

For instance, say I'm listening at /:

func main() {
	http.HandleFunc("/", provideMainContent)
}

func provideMainContent(w http.ResponseWriter, r *http.Request) {
    /// Bunch of code, looks up details in databases, parses, then returns
}

Should the bunch of code in provideMainContent be wrapped in a goroutine so it doesn't slow down any potential requests that come after the fact ?

答案1

得分: 10

简短回答,不需要。

来自http.Serve的GoDoc:

Serve函数接受来自监听器l的传入HTTP连接,并为每个连接创建一个新的服务goroutine。服务goroutine读取请求,然后调用处理程序来回复请求。

然而,正如由@Mellow Marmot提到的问题中所提到的,有些情况下你可能希望在从处理程序返回时生成一个goroutine来进行一些处理,这样请求者就不必等待所有处理完成才能获得响应。

英文:

Short answer, No

GoDoc from http.Serve :

Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

However as mentioned in the question linked by @Mellow Marmot, there might be cases where you might want to spawn a goroutine to do some processing while you return from the handler so that the requester does not have to wait for all the processing to be done to get a response.

huangapple
  • 本文由 发表于 2016年11月4日 11:09:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/40414685.html
匿名

发表评论

匿名网友

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

确定