I'm developing a web application in go and I know in http package, every request is run in a separate goroutine. Now, if the code inside this goroutine queries a database then wait and using db result calls a remote api to fetch some related data and son on and so forth, shall I run each of these calls in separate goroutine or the one provided by http is enough?
1条回答 默认 最新
donvo24600 2017-04-29 10:49关注That depends on what you're doing.
Each HTTP request should be handled sequentially. That is to say, you shouldn't fire off a goroutine for handling the request itself:
func myHandler(w http.ResponseWriter, r *http.Request) { go func(w http.ResponseWriter, r *http.Request) { // There's no advantage to this }(w,r) }However, there are still times when goroutines make sense when handling an HTTP response. The two most common situations are probably:
-
You want to do something in parallel.
func myHandler(w http.ResponseWriter, r *http.Request) { wg := &sync.WaitGroup{} wg.Add(2) go func() { defer wg.Done() /* query a remote API */ }() go func() { defer wg.Done() /* query a database */ }() wg.Wait() // finish handling the response } -
You want to finish handling something after responding to the HTTP request, so that the web client doesn't have to wait.
func myHandler(w http.ResponseWriter, r *http.Request) { // handle request w.Write( ... ) go func() { // Log the request, and send an email }() }
解决 无用评论 打赏 举报-