我想知道每当请求进来时 goroutine 和 go web 服务器究竟是如何工作的:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,
每个/调用handler. 这是否意味着每个请求都会产生自己的 goroutine?或者它会产生自己的process还是thread?有没有关于这些请求如何获得自己的 goroutine 的文档?
其他语言如何处理这个请求?例如,Python flask 是否为每个请求启动自己的进程?
谢谢,
Go 的 HTTP 服务器(in net/http)根据http://golang.org/pkg/net/http/#Server.Serve的文档为每个请求生成一个 goroutine(不是线程)-
Serve 接受 Listener l 上的传入连接,为每个连接创建一个新的服务 goroutine。服务 goroutine 读取请求,然后调用 srv.Handler 来回复它们。
其他语言以多种方式处理这个问题,包括:
我建议阅读https://www.digitalocean.com/community/tutorials/a-comparison-of-rack-web-servers-for-ruby-web-applications以了解一些 Ruby Web 服务器如何工作的示例东西(包括上面的方法),以及用于 Python 的https://www.digitalocean.com/community/tutorials/a-comparison-of-web-servers-for-python-based-web-applications,这应该给一些洞察力。
| 归档时间: |
|
| 查看次数: |
1628 次 |
| 最近记录: |