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

查看:38
本文介绍了Go 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 中)根据 http://golang.org/pkg/net/http/#Server.Serve-

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 接受 Listener 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:

  • 基于事件的架构 ala 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,它应该给出一些见解.

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.

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

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