This question already has an answer here:
I have a question about goroutines in http.
In the code below is a simple web server.
If 5 people access the server, 2 people go in function handler1()
and 3 people go in handler2()
, golang will create 5 goroutines or do I need to put the reserved word go
?
e.g. 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))
}
</div>
No matter how you start a net/http
server, it ends up calling 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.