Search code examples
gohttpserver

How to handle low-level net/http errors?


With my golang net/http server, I occasionally get errors like

2017/08/04 15:06:25 http: Accept error: accept tcp 127.0.0.1:80: accept4: too many open files; retrying in 1s

on stderr. There might be a bug with a missing Close() somewhere, but this is not what my question is about.

What I would like to know is whether there is an easy way to catch these or similar errors programmatically in go? I only know about this error because it's logged. ListenAndServe() does not return an error. Is there some other way to get notified of errors like these? Specifically: how do I access the errors of the underlying listener? ListenAndServe() does not return errors from the underlying listener (at least not all of them).

(edited)


Solution

  • If you look at how (*http.Server).Serve() is implemented here, it is clear that you can just define your own class that implements net.Listener and give it to the Serve() function, instead of using ListenAndServe(), which puts a default listener there. Make it panic on error and later recover from that panic in your code, or implement any other error handling logic.