article

manners — gracefully shutdown Go server

Manners is a Go package from Braintree that allows you to create a web server that you can gracefully shutdown.

When creating a standard HTTP server in Go, it is common to use ListenAndServe to start listening to incoming connections and launch request handlers. ListenAndServe blocks until there is an error. What if you want to unblock the server and stop it from running? With Manners, you can do it.

How to use manners

Just a create a new server like this:

func main() {
  handler := MyHTTPHandler()
  server := manners.NewServer()
  server.ListenAndServe(":7000", handler)
}

As with the standard net/http package, server.ListenAndServe from the above example will block. However, when you want to shut it down, pass true to the server.Shutdown channel from another goroutine (for example, from a signal handler):

server.Shutdown <- true

Manners then will wait until all requests are finished serving, and shut down the server.

Where to get manners

Manners can be installed with go get:

go get github.com/braintree/manners

Manners requires Go 1.3, since it’s the first Golang version to introduce ConnState hooks.

Project information

GitHub: https://github.com/braintree/manners
Documentation: https://godoc.org/github.com/braintree/manners
License: MIT

2 comments

  1. You mention that the shutdown process will wait until all active requests have completed. What about new requests that are invoked after the shutdown operation begins? Will those requests be rejected?

    1. Paul, as far as I understand, it will stop accepting new requests and release this port, so that you can immediately bind it to a new process (At least that’s what https://github.com/tylerb/graceful — my new preferred graceful shutdown handler — does).

Comments are closed.