A lightweight and flexible graceful shutdown manager for Go applications.
It helps you coordinate cleanup of multiple components (servers, workers, connections, etc.) when your program receives termination signals (SIGINT, SIGTERM).
- Register any component that implements a simple
Gracefulinterface - Per-component timeout with automatic cancellation
- Parallel or sequential shutdown modes
- Custom before / after hooks
- Handles OS signals (
SIGINT,SIGTERMby default, configurable) - Collects and returns shutdown errors
go get github.com/bi0dread/gracefulpackage main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/bi0dread/graceful"
)
// Example: wrap an HTTP server to support graceful shutdown
type HTTPServer struct {
srv *http.Server
}
func (h *HTTPServer) Shutdown(ctx context.Context) error {
fmt.Println("Shutting down HTTP server...")
return h.srv.Shutdown(ctx)
}
func main() {
// Create manager with 5s timeout per component
g := graceful.New(5 * time.Second)
// Example HTTP server
server := &HTTPServer{srv: &http.Server{Addr: ":8080"}}
// Register with optional before/after hooks
g.Register(
server,
func() { fmt.Println("Before shutting down HTTP server") },
func(err error) { fmt.Println("After shutdown, err:", err) },
)
// Block until termination signal (Ctrl+C / kill)
errs := g.WaitForSignal(true) // true = shutdown in parallel
// Report errors if any
for _, err := range errs {
fmt.Println("Shutdown error:", err)
}
}type Graceful interface {
Shutdown(ctx context.Context) error
}Any component implementing Shutdown(ctx) can be managed.
g := graceful.New(timeout time.Duration)timeout: maximum shutdown time for each component.
g.Register(source Graceful, before func(), after func(err error))source: the component to managebefore: optional hook called before shutdownafter: optional hook called after shutdown with error result
errs := g.WaitForSignal(parallel bool, signals ...os.Signal)parallel: iftrue, shutdown all in parallel; iffalse, shutdown sequentiallysignals: override default (SIGINT,SIGTERM)
Returns []error with details of failed shutdowns.
This package comes with full test coverage:
go test ./...Tests include:
- Sequential vs parallel shutdown
- Timeout handling
- Error propagation
- Before/after hooks
- Signal handling
MIT License. See LICENSE for details.