Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get notified when http.Server starts listening

Tags:

go

When I look at the net/http server interface, I don't see an obvious way to get notified and react when the http.Server comes up and starts listening:

ListenAndServe(":8080", nil)

The function doesn't return until the server actually shuts down. I also looked at the Server type, but there doesn't appear to be anything that lets me tap into that timing. Some function or a channel would have been great but I don't see any.

Is there any way that will let me detect that event, or am I left to just sleeping "enough" to fake it?

like image 985
sjlee Avatar asked Jun 16 '17 20:06

sjlee


1 Answers

ListenAndServe is a helper function that opens a listening socket and then serves connections on that socket. Write the code directly in your application to signal when the socket is open:

l, err := net.Listen("tcp", ":8080")
if err != nil {
    // handle error
}

// Signal that server is open for business. 

if err := http.Serve(l, rootHandler); err != nil {
    // handle error
}

If the signalling step does not block, then http.Serve will easily consume any backlog on the listening socket.

Related question: https://stackoverflow.com/a/32742904/5728991

like image 157
Bayta Darell Avatar answered Sep 17 '22 23:09

Bayta Darell