Go web server requests spawn its own goroutine?

后端 未结 1 959
野性不改
野性不改 2021-01-14 07:01

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.Fprint         


        
1条回答
  •  臣服心动
    2021-01-14 07:42

    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.

    0 讨论(0)
提交回复
热议问题