sjlee
sjlee

Reputation: 7886

get notified when http.Server starts listening

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?

Upvotes: 12

Views: 3834

Answers (1)

Thundercat
Thundercat

Reputation: 121119

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

Upvotes: 24

Related Questions