英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论