Web服务器请求会生成自己的goroutine吗? [英] Go web server requests spawn its own goroutine?

查看:94
本文介绍了Web服务器请求会生成自己的goroutine吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道goroutine和Go Web服务器在请求进入时到底如何工作:

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)
}

在此代码中

  1. 每个对/的请求都调用handler.这是否意味着每个请求都会生成自己的goroutine?还是产生自己的processthread?是否有任何文档说明这些请求如何获得自己的goroutine?

  1. Every request to / calls the handler. Does this mean each request spawns its own goroutine? Or does it spawns its own process or thread? Is there any documentation on how those requests get its own goroutine?

其他语言如何处理此请求?例如,Python flask是否为每个请求启动自己的进程?

How do other languages handle this request? For example, does Python flask launch its own process for each request?

谢谢

推荐答案

Go的HTTP服务器(在net/http中)根据

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 -

服务在侦听器l上接受传入连接,从而为每个连接创建一个新的服务goroutine.服务goroutine读取请求,然后调用srv.Handler对其进行回复.

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:

我建议阅读

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.

这篇关于Web服务器请求会生成自己的goroutine吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆