Documentation ¶
Overview ¶
Package httpdshutdown allows for graceful shutdown of http daemons. This package exports a `Watcher` that exports methods for signal handling, connection state observation, and shutdown hook registration and execution.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ShutdownHook ¶
type ShutdownHook func() error
ShutdownHook is the type callers will implement in their own daemon shutdown handlers.
type Watcher ¶
type Watcher struct {
// contains filtered or unexported fields
}
Watcher manages the execution of shutdownHooks.
func NewWatcher ¶
func NewWatcher(timeoutMS int, hooks ...ShutdownHook) (*Watcher, error)
NewWatcher construct a Watcher with a timeout and an optional set of shutdown hooks to be called at the time of shutdown.
The first argument is a timeout in milliseconds that will trigger shutdown hooks even if the daemon still has open connections. Further arguments are a variadic list of type `ShutDownHook`.
Example instantiation:
watcher, watcher_err := httpdshutdown.NewWatcher(2000, sampleShutdownHook1, sampleShutdownHook2)
func (*Watcher) OnStop ¶
OnStop will be called by a daemon's signal handler when it is time to shutdown. If there are any shutdown handlers, they will be called. The timeout set on the watcher will be honored. Typically this is called via `SigHandle` as your signal handler.
func (*Watcher) RecordConnState ¶
RecordConnState counts open and closed connections. This function can be assigned to a `http.Server`'s `ConnState` field.
Example use:
srv := &http.Server{ Addr: ":8080", ReadTimeout: 3 * time.Second, WriteTimeout: 3 * time.Second, ConnState: func(conn net.Conn, newState http.ConnState) { log.Printf("(1) NEW CONN STATE:%v\n", newState) watcher.RecordConnState(newState) } }
func (*Watcher) RunHooks ¶
RunHooks executes registered hooks, each of which blocks. Typically this is called automatically by `OnStop`.
func (*Watcher) SigHandle ¶
SigHandle is an example of a typical signal handler that will attempt a graceful shutdown for a set of known signals. The first argument is your signal channel, and the second argument is the channel that can be polled for exit status codes.
This should be called prior to starting your http daemon. Place it in its own goroutine so signals can be recorded after the daemon has taken over control of the main thread.
Example use:
go func() { sigs := make(chan os.Signal, 1) exitcode := make(chan int, 1) signal.Notify(sigs) go watcher.SigHandle(sigs, exitcode) code := <-exitcode log.Printf("exit with code:%d", code) os.Exit(code) }()