How to use goroutine inside AppEngine?

Issue

I’m using Cloud Endpoints and Go and I’m trying to call a method in asynchronous way by using a goroutine.

When I’m running the following code locally I can see the debug prints but on the server it looks like the method did not get called.

I’m basically trying to do

go doStuff()

return type 

Solution

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
}

Answered By – icza

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.