I am playing around with Go a bit and I’ve a problem that I am unable to solve.
The following code is the least possible code that reproduces my problem. The goal
of the original code is to delegate http request to goroutines. Each goroutine
does a bit of heavy image calculations and is supposed to respond.
package main
import (
"fmt"
"runtime"
"net/http"
)
func main() {
http.HandleFunc("/", handle)
http.ListenAndServe(":8080", nil)
}
func handle(w http.ResponseWriter, r *http.Request) {
// the idea is to be able to handle several requests
// in parallel
// the "go" is problematic
go delegate(w)
}
func delegate(w http.ResponseWriter) {
// do some heavy calculations first
// present the result (in the original code, the image)
fmt.Fprint(w, "hello")
}
In the case of a go delegate(w) I get no response, without the go it
works out nicely.
Can anyone explain what’s going on? Thanks a lot!
ListenAndServealready launches goroutines to call your handler function, so you shouldn’t do it yourself.Here’s the code of the relevant functions from the package source :
So your code should simply be