http 中的协程

Goroutines in http

我对 http 中的 goroutines 有疑问。

下面的代码是一个简单的网络服务器。

如果5个人访问服务器,2个人进入函数handler1(),3个人进入handler2(),golang会创建5个goroutines还是需要把保留字go?

例如go http.HandleFunc("/h1", handler1)

package main

import( 
      "fmt"
      "log"
      "net/http"
 )

func handler1(w http.ResponseWriter, r *http.Request) {
      fmt.Println(w, "Hello 01!")
}

func handler2(w http.ResponseWriter, r *http.Request) {
      fmt.Println(w, "Hello 02")
}

func main() {
      http.HandleFunc("/h1", handler1)
      http.HandleFunc("/h2", handler2)
      log.Fatal(http.ListenAndServe(":8080", nil))
}

无论您如何启动 net/http 服务器,它最终都会调用 Serve which:

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.