Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situation will http.ListenAndServe return

Tags:

http

go

I see a lot of code do this kind of thing:

log.Fatal(http.ListenAndServe(":8080",nil))

I have never seen the http server return an error, but I would like to understand more about the possibility what types of failure scenarios I can encounter.

Will it stop if my handler code panics? Will it only return in the case where it can't bind initially?

What is the best practice for making sure the server stays active to the highest degree possible?

like image 539
captncraig Avatar asked Dec 08 '25 10:12

captncraig


1 Answers

Will it stop if my handler code panics?

No. The built-in http server recovers from panics and logs them.

Will it only return in the case where it can't bind initially?

That's the usual reason, though it's possible that some other error could force the listener to close.

What is the best practice for making sure the server stays active to the highest degree possible?

If the http server's main loop exits, it's likely a fatal error that you don't want to try and recover from. If that call returns when trying to bind the address, you could check for the address in use error, then wait and try again.

// Example to show the error types and fields on a *nix system.
// You should check the validity of these assertions if you don't want to 
// panic. Due to the fact that this reaches into syscall, it's probably 
// not much better than checking the string for "address already in use"

if err.(*net.OpError).Err.(*os.SyscallError).Err == syscall.EADDRINUSE {
    fmt.Println("Address in use")
}

Remember that ListenAndServe is actually 2 calls, and you can separate them yourself. It creates a net.Listener, then gives it to an http.Server's Serve(l net.Listener) method.

like image 91
JimB Avatar answered Dec 10 '25 04:12

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!