1024programmer Java Why is the goroutine blocking the main functionality of this http server?

Why is the goroutine blocking the main functionality of this http server?

I want to set up an http server, httprouter listens to two ports 8888, 8080 like the following code.

package main

 import (

 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 .8080If 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 .

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/764808

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top