Home >Backend Development >Golang >How to Gracefully Stop a Go Listening Server Without Errors?

How to Gracefully Stop a Go Listening Server Without Errors?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 00:26:11690browse

How to Gracefully Stop a Go Listening Server Without Errors?

How to Gracefully Stop a Listening Server in Go

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn