http.ListenAndServe(), if there aren’t any error, block the execution so the following lines won’t be executed.
go func() {
err := http.ListenAndServe("127.0.0.1:9090", nil)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(Success) // Not executed
}()
select{}
I could log the success message outside the goroutine but it’s not ideal since it can be executed before a possible error occur.
0
The only initialization that can fail is creating the listener. Break that out as a separate step, log and then start the listen loop.
l, err := net.Listen("tcp", "127.0.0.1:9090")
if err != nil {
log.Fatal(err)
}
fmt.Println("success")
log.Fatal(http.Serve(l, nil)) // runs until server fails.
Penny Stevens is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.