The Go runtime for AppEngine supports goroutines, quoting from the doc: Go Runtime Environment: Introduction:
The Go runtime environment for App Engine provides full support for goroutines, but not for parallel execution: goroutines are scheduled onto a single operating system thread.
The problem is that when your HandleFunc()
or Handler.ServeHTTP()
returns, the AppEngine platform (and the http
package too) does not wait for any goroutines started by the handler function to complete.
Quoting from the doc: Handling Requests: Responses:
App Engine calls the handler with a Request
and a ResponseWriter
, then waits for the handler to write to the ResponseWriter
and return. When the handler returns, the data in the ResponseWriter
's internal buffer is sent to the user.
You have to synchronize your request handling and goroutine, and only return once the goroutine has completed its work, for example:
func doStuff(done chan int) {
// Do your stuff
// and finally signal that you're done:
done <- 0
}
func someHandler(w http.ResponseWriter, r *http.Request) {
done := make(chan int)
go doStuff(done)
// Wait for the goroutine to complete:
<-done
}