我在 Golang 中编写了一个 httpserver,但我发现当来自网络浏览器的多个请求时,http.HandleFunc 将被阻止。我怎样才能让服务器同时处理多个请求?谢谢。
我的代码是:
func DoQuery(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Printf("%d path %s\n", time.Now().Unix(), r.URL.Path)
time.Sleep(10 * time.Second)
fmt.Fprintf(w, "hello...")
//why this function block when multi request ?
}
func main() {
fmt.Printf("server start working...\n")
http.HandleFunc("/query", DoQuery)
s := &http.Server{
Addr: ":9090",
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
//MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
fmt.Printf("server stop...")
}
我运行了您的代码,一切都按预期工作。我同时执行了两个请求 (curl localhost:9090/query),它们都在 10 秒后一起完成。也许问题出在其他地方?这是我使用的命令:time curl -s localhost:9090/query | echo $(curl -s localhost:9090/query) – tjameson
感谢
这很奇怪。 当我从 chrome 请求相同的 url 时,发送两个请求不能同时处理,但使用 cur 测试可以同时处理。 但是当我发送两个请求使用不同的 url 时,它可以同时处理。
[root@localhost httpserver]# ./httpServer
服务器开始工作...
1374301593 路径/query?form=chrome
1374301612 路径/query?from=cur2
1374301614 路径/query?from=cur1
1374301618 路径/query?form=chrome
1374301640 路径/query?form=chrome2
1374301643 路径/query?form=chrome1
*1374301715 路径/query?form=chrome
1374301725 路径/query?form=chrome*
**1374301761 路径/query?form=chrome1
1374301763 路径/query?form=chrome2**
最佳答案
是的,标准的 HTTP 服务器会为每个请求启动一个新的 goroutine。根据操作系统设置,您应该能够并行执行数千个请求。
您的浏览器可能会限制发送到一台服务器的请求数量;确保您正在使用没有该限制/“优化”的客户端进行测试。
Reliably Go 文档解释了 Http Server 为每个请求创建一个新的 gorotine:http://golang.org/pkg/net/http/#Server.Serve
关于go - 在 Golang 中,http.HandleFunc 是 block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17758345/