Documentation
¶
Overview ¶
Package shutdown provides a declarative graceful shutdown orchestrator for Go microservices.
It works with any component that implements the Closer interface — HTTP servers, gRPC servers, database pools, message consumers, background workers, and more.
Components are organized into priority groups. Groups execute sequentially (lowest priority number first), while components within the same group shut down in parallel.
Index ¶
- type Closer
- type CloserFunc
- type ComponentOption
- type Manager
- func (m *Manager) Listen(ctx context.Context) error
- func (m *Manager) Register(name string, closer Closer, opts ...ComponentOption) *Manager
- func (m *Manager) RegisterFunc(name string, fn func(ctx context.Context) error, opts ...ComponentOption) *Manager
- func (m *Manager) Shutdown(ctx context.Context) error
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Closer ¶
Closer is the interface that any managed component must implement. Close should gracefully shut down the component, respecting the provided context for cancellation and deadlines.
Many Go types already satisfy this interface or can be easily adapted. For example, *http.Server has a Shutdown(ctx) method that matches the signature.
type CloserFunc ¶
CloserFunc is an adapter that allows ordinary functions to be used as Closer. It follows the same pattern as net/http.HandlerFunc.
type ComponentOption ¶
type ComponentOption func(*componentConfig)
ComponentOption configures a single registered component.
func WithComponentTimeout ¶
func WithComponentTimeout(d time.Duration) ComponentOption
WithComponentTimeout overrides the global timeout for this component. If the component timeout is longer than the remaining global timeout, the global timeout takes precedence (context deadlines propagate).
func WithPriority ¶
func WithPriority(p int) ComponentOption
WithPriority sets the shutdown priority for a component. Lower numbers shut down first. Components with the same priority shut down in parallel. The default priority is assigned based on registration order (first registered = lowest priority = shuts down first).
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager orchestrates graceful shutdown of all registered components.
Components are shut down in priority order: lower priority numbers shut down first. Components with the same priority shut down in parallel. If no priority is set, components shut down in registration order.
Manager is safe for concurrent use.
Example (Basic) ¶
package main
import (
"context"
"fmt"
"io"
"log/slog"
"time"
"github.com/krus210/shutdown"
)
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func main() {
mgr := shutdown.New(
shutdown.WithTimeout(5*time.Second),
shutdown.WithLogger(discardLogger()),
)
mgr.RegisterFunc("http-server", func(_ context.Context) error {
fmt.Println("http server stopped")
return nil
})
mgr.RegisterFunc("database", func(_ context.Context) error {
fmt.Println("database connection closed")
return nil
})
_ = mgr.Shutdown(context.Background())
}
Output: http server stopped database connection closed
Example (CloserInterface) ¶
package main
import (
"context"
"fmt"
"io"
"log/slog"
"time"
"github.com/krus210/shutdown"
)
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
// DBConn demonstrates implementing the Closer interface.
type DBConn struct{}
// Close implements shutdown.Closer.
func (d *DBConn) Close(_ context.Context) error {
fmt.Println("db connection closed")
return nil
}
func main() {
mgr := shutdown.New(
shutdown.WithTimeout(5*time.Second),
shutdown.WithLogger(discardLogger()),
)
mgr.Register("database", &DBConn{})
_ = mgr.Shutdown(context.Background())
}
Output: db connection closed
Example (Priority) ¶
package main
import (
"context"
"fmt"
"io"
"log/slog"
"time"
"github.com/krus210/shutdown"
)
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func main() {
mgr := shutdown.New(
shutdown.WithTimeout(5*time.Second),
shutdown.WithLogger(discardLogger()),
)
mgr.RegisterFunc("http-server", func(_ context.Context) error {
fmt.Println("1: http server stopped")
return nil
}, shutdown.WithPriority(0))
mgr.RegisterFunc("worker", func(_ context.Context) error {
fmt.Println("2: worker stopped")
return nil
}, shutdown.WithPriority(1))
mgr.RegisterFunc("database", func(_ context.Context) error {
fmt.Println("3: database closed")
return nil
}, shutdown.WithPriority(2))
_ = mgr.Shutdown(context.Background())
}
Output: 1: http server stopped 2: worker stopped 3: database closed
func (*Manager) Listen ¶
Listen blocks until an OS signal is received (SIGINT and SIGTERM by default), then initiates graceful shutdown. A second signal forces immediate exit via os.Exit(1).
Listen also triggers shutdown if the provided context is cancelled.
Returns an aggregated error if any component failed to shut down.
func (*Manager) Register ¶
func (m *Manager) Register(name string, closer Closer, opts ...ComponentOption) *Manager
Register adds a component to the shutdown manager. Components are stopped in reverse registration order by default, or by explicit priority (lower number = stops first).
Register returns the Manager to allow method chaining.
Register panics if closer is nil.
func (*Manager) RegisterFunc ¶
func (m *Manager) RegisterFunc(name string, fn func(ctx context.Context) error, opts ...ComponentOption) *Manager
RegisterFunc is a convenience method that registers a function as a Closer. It wraps fn in a CloserFunc and delegates to Manager.Register.
func (*Manager) Shutdown ¶
Shutdown initiates graceful shutdown of all registered components. Components are stopped according to their priority: lower priority numbers first. Components with the same priority are stopped in parallel.
Shutdown is idempotent — calling it multiple times is safe. Subsequent calls block until the first invocation completes and return the same error.
type Option ¶
type Option func(*managerConfig)
Option configures the Manager.
func WithLogger ¶
WithLogger sets a custom *slog.Logger for structured shutdown logging. The default is slog.Default.
func WithOnError ¶
WithOnError sets a callback that is invoked when a component fails to shut down. The callback receives the component name and the error.
func WithSignals ¶
WithSignals sets the OS signals that trigger graceful shutdown. The default signals are SIGINT and SIGTERM.
func WithTimeout ¶
WithTimeout sets the global shutdown timeout. The default is 30 seconds. This timeout is applied as a context deadline wrapping the parent context passed to Manager.Shutdown or Manager.Listen.