Home > Backend Development > Golang > How Can I Gracefully Stop a Go Server and Avoid 'Use of Closed Network Connection' Errors?

How Can I Gracefully Stop a Go Server and Avoid 'Use of Closed Network Connection' Errors?

Susan Sarandon
Release: 2024-12-12 11:28:09
Original
334 people have browsed it

How Can I Gracefully Stop a Go Server and Avoid

Handling Server Stoppage Gracefully in Go

Problem Introduction

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.

Solution Approach

To address this issue, we can leverage the done channel to signal the server's impending shutdown.

Improved Server Logic

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))
  }
}
Copy after login
  • The done channel allows us to send a signal to the serve() function before closing the listener.
  • When stop() is called, it sends a value to done, which unblocks the select statement in serve().
  • This ensures that when the listener is closed, the serve() function gracefully exits without reporting the "use of closed network connection" error.

Updated Stop Method

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
}
Copy after login

Evaluation and Conclusion

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template