0

Still fully getting my head around goroutines and channels, so I might be doing something obviously wrong. I have a service that runs a websocket server and public route used to upgrade clients from https to wss. I am trying to attach some tear-down code for one of the routines, but the second go call seems to block the main function's execution. I reach Println 5 on the console on boot up. The rest of my program is happily working. I just can't kill it with a ctrl+C (nor does it do it's required tear down after a manual shut down).

Here's the relevant code (the complete main file minus the streamAddr var and the imports):

func main() {
    fmt.Println(1)
    flag.Parse()
    log.SetFlags(0)

    fmt.Println(2)
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    fmt.Println(3)
    hub := socktools.NewHub()
    go hub.Run()

    fmt.Println(4)
    http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
        socktools.ServeWs(hub, w, r)
    })

    fmt.Println(5)
    go log.Fatal(http.ListenAndServe(*streamAddr, nil))

    fmt.Println(6)

    select {
    case <-interrupt:
        fmt.Println("Interrupt heard...")
        close(hub.KillChan)
        <-hub.KilledChan
        fmt.Println("Ending main function")
        return
   }
}

Why is go log.Fatal(http.ListenAndServe(*streamAddr, nil)) blocking? I thought that the go keyword instantly made it asynchronous? Am I using it wrong here?

1 Answer 1

3

You are essentially calling go log.Fatal(variable), so the async call is log.Fatal, but it has to know what variable is at that moment, so it first has to call http.ListenAndServe to see what it returns. But http.ListenAndServe blocks.

You need to do:

go func() {
    log.Fatal(http.ListenAndServe(*streamAddr, nil))
}()
1
  • Thank you! I knew it was some oversight like that.
    – K. Rhoda
    May 11, 2018 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.