我应该使用带有http.ListenAndServe的goroutine吗?

Dou*_*ith 2 go goroutine

如果我http.ListenAndServe在用户点击URL时使用提供响应,我是否应该将该函数中的相应操作作为goroutine触发?

例如,说我正在听/:

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

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

是否应该将一堆代码provideMainContent包装在一个goroutine中,这样它不会减慢事后发生的任何潜在请求?

Joh*_*yil 8

简短回答,不

GoDoc来自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.

但是,如链接的问题中所提到的@Mellow Marmot,可能存在这样的情况:当您从处理程序返回时,您可能希望生成一个goroutine来执行某些处理,以便请求者不必等待所有处理完成以获得响应.