dongyao8698 2015-06-29 05:30
浏览 94
已采纳

Web服务器请求会生成自己的goroutine吗?

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,

  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?

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

Thanks,

  • 写回答

1条回答 默认 最新

  • dtnpf35197 2015-06-29 06:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 阿里云python代码求解
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路