In Go, gracefully stopping a listening server is essential to avoid abrupt termination and potential data loss. One challenge is discerning the specific error that indicates the listener has closed, as it's not explicitly exported in the standard library.
To address this issue, we can leverage the done channel to signal the server's impending shutdown.
The modified serve() function now handles errors differently:
func (es *EchoServer) serve() { for { conn, err := es.listen.Accept() if err != nil { select { case <-es.done: // If we called stop() then there will be a value in es.done, so // we'll get here and we can exit without showing the error. default: log.Printf("Accept failed: %v", err) } return } go es.respond(conn.(*net.TCPConn)) } }
The modified stop() method now sends a signal to the done channel before closing the listener:
// Stop the server by closing the listening listen func (es *EchoServer) stop() { es.done <- true // We can advance past this because we gave it a buffer of 1 es.listen.Close() // Now the Accept will have an error above }
This approach offers an improved and graceful way of handling server stoppage in Go. By utilizing the done channel, we can prevent the display of unwanted error messages while still maintaining control over server termination.
The above is the detailed content of How Can I Gracefully Stop a Go Server and Avoid 'Use of Closed Network Connection' Errors?. For more information, please follow other related articles on the PHP Chinese website!