I want to set up an http server, httprouter listens to two ports 8888
, 8080
like the following code.
package main import ( "fmt" "github.com/julienschmidt/httprouter" "log" "net/http" ) func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome!\n") } func main() { router := httprouter.New() router.GET("/", Index) fmt.Println("listen on 8080") // this is where blocked go log.Fatal(http.ListenAndServe(":8080", router)) fmt.Println("listen on 8888") log.Fatal(http.ListenAndServe(":8888", router)) }
But it doesn’t work, my server can only listen to .8080
If I make some changes:
go func() { log.Fatal(http.ListenAndServe(":8080", router)) }()
It works fine with both 8080
and 8888
. Why? Is it about closure
or something else?
1> hobbs..:
Function values and parameters are evaluated as usual in the goroutine call
– Go to language specification, “Go to declaration”.
You are creating a goroutine that calls log.Fatal
, but the parameters are log.Fatal
pre-evaluated, in the main goroutine. And Fatal
demonstrates the return value http.ListenAndServe
. Therefore, the new goroutine does not start ListenAndServe
until it returns .