我正在尝试使用Go语言,并遇到了一个无法解决的问题。
以下代码是能够重现我的问题的最小代码。原始代码的目标是将http请求委托给goroutine。每个goroutine都会进行一些复杂的图像计算,并应该做出响应。
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")
}
在使用go delegate(w)
时,我没有得到任何响应,在去掉go
后就可以顺利工作。
有人能解释一下发生了什么吗?非常感谢!