Reputation: 953
What is the difference between
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
go srv.Serve(ln)
And
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
?
I am creating my own ListenAndServe (first code snippet) so that I can execute code and send requests to my server right after calling my ListenAndServe. However, I cannot use tcpKeepAliveListener as it is not exported. srv.Serve(ln) also works but I don't know if I am missing something if I go with the first way.
Upvotes: 0
Views: 2365
Reputation: 120951
Given the goal of sending requests to the server after starting the server, the application must execute listen and serve separately.
The approach of sending requests after starting ListenAndServe
in a goroutine does not guarantee that the server is listening when the requests are sent. It is possible for main goroutine to continue executing to send before goroutine executes at all.
The tcpKeepAliveListener
is short. If you need that functionality, then copy the code to your application.
Here's the code to use:
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
go func() {
log.Fatal(srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}))
}()
// The Serve loop is not guaranteed to be running at this point, but
// the listening socket is open and requests to the socket will queue.
... send requests here
Upvotes: 1