英文:
Go web server requests spawn its own goroutine?
问题
我想知道每当请求到来时,goroutine和Go Web服务器是如何工作的:
在这段代码中,
-
每个对
/
的请求都会调用handler
函数。这是不是意味着每个请求都会生成自己的goroutine?还是生成自己的进程
或线程
?有没有关于这些请求如何获得自己的goroutine的文档? -
其他编程语言是如何处理这个请求的?例如,Python的Flask框架是为每个请求启动自己的进程吗?
谢谢。
英文:
I want to know how exactly goroutine and go web server works whenever requests come in:
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)
}
In this code,
-
Every request to
/
calls thehandler
. Does this mean each request spawns its own goroutine? Or does it spawns its ownprocess
orthread
? Is there any documentation on how those requests get its own goroutine? -
How do other languages handle this request? For example, does Python flask launch its own process for each request?
Thanks,
答案1
得分: 7
Go的HTTP服务器(在net/http
中)根据http://golang.org/pkg/net/http/#Server.Serve文档,为每个请求生成一个goroutine(而不是线程)。
> Serve在监听器l上接受传入的连接,为每个连接创建一个新的服务goroutine。服务goroutine读取请求,然后调用srv.Handler来回复它们。
其他语言以多种方式处理这个问题,包括:
- 基于事件的架构,比如node.js1
- 多进程和/或多线程(或两者兼有),其中“管理器”根据阻塞情况(以及非阻塞情况)切换活动线程
我建议阅读https://www.digitalocean.com/community/tutorials/a-comparison-of-rack-web-servers-for-ruby-web-applications,了解一些Ruby Web服务器的工作方式(包括上述方法),以及https://www.digitalocean.com/community/tutorials/a-comparison-of-web-servers-for-python-based-web-applications,了解Python的一些见解。
英文:
Go's HTTP server (in net/http
) spawns a goroutine (not a thread) per request as per the docs for http://golang.org/pkg/net/http/#Server.Serve -
> Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them.
Other languages handle this in many ways, including:
- Event-based architectures ala node.js1 and
- Multiple processes and/or threads (or both) where the "manager" switches between the active thread based on what is blocking (and what isn't)
I'd suggest reading https://www.digitalocean.com/community/tutorials/a-comparison-of-rack-web-servers-for-ruby-web-applications for an example of how some of the Ruby web servers do things (which include the approaches above), and https://www.digitalocean.com/community/tutorials/a-comparison-of-web-servers-for-python-based-web-applications for Python, which should give some insight.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论