Home >Backend Development >Golang >How to Gracefully Stop a Go Listening Server Without Errors?
In Go, the Listen.Accept function blocks execution until a connection is accepted. This makes it difficult to gracefully stop a listening server because you can't tell the difference between an error and a closed connection.
One solution is to use a done channel to signal when the server should stop listening. This allows you to close the listening socket without getting an error.
Here is an example of how to do this:
// Echo server struct type EchoServer struct { listen net.Listener done chan bool } // Listen for incoming connections 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)) } } // Stop the server by closing the listening listen func (es *EchoServer) stop() { es.done <- true // We can advance past this because we gave it buffer of 1 es.listen.Close() // Now it the Accept will have an error above }
This code uses a done channel to signal when the server should stop listening. When the stop method is called, it sends a value to the done channel, which causes the serve method to exit.
This allows you to gracefully stop a listening server without getting an error.
The above is the detailed content of How to Gracefully Stop a Go Listening Server Without Errors?. For more information, please follow other related articles on the PHP Chinese website!