2016-11-04 57 views
0

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

例如,说我在听/

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

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

应的代码provideMainContent这帮在goroutine中被包裹,因此不会减慢事后说来任何潜在的请求?

+2

ListenAndServe()方法为你做,我们不必处理,只记得每个处理程序运行在不同的goroutine –

回答

6

简短的回答,没有

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链接的问题中提到,有可能是,你可能要产生一个够程做一些案件在从处理程序返回时进行处理,以便请求者无需等待所有处理来完成响应。