shutdown

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package shutdown coordinates a process's graceful shutdown — registered hooks run in LIFO order on signal (SIGINT/SIGTERM) or explicit Stop(), each with its own timeout, errors are aggregated rather than swallowed.

Designed for plain `func main()` programs that don't use fx. fx-based services already get this for free via lifecycle hooks.

c := shutdown.New(shutdown.WithGraceWindow(30 * time.Second))
c.Register("http-server", server.Stop)
c.Register("db", db.Close)
if err := c.Run(ctx); err != nil {
    log.Fatal(err)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Coordinator

type Coordinator struct {
	// contains filtered or unexported fields
}

Coordinator manages a stack of shutdown hooks.

func New

func New(opts ...Option) *Coordinator

New constructs a Coordinator with the supplied options.

func (*Coordinator) Register

func (c *Coordinator) Register(name string, fn Hook)

Register adds a hook. Hooks run in LIFO order, so register cheap-to-stop things last (servers before databases, for example).

func (*Coordinator) Run

func (c *Coordinator) Run(ctx context.Context) error

Run blocks until ctx is cancelled, a configured signal arrives, or Stop is called, then runs all registered hooks in LIFO order. Returns the joined error of any hooks that failed or timed out.

func (*Coordinator) Stop

func (c *Coordinator) Stop()

Stop triggers shutdown explicitly. Safe to call multiple times — only the first call has effect.

type Hook

type Hook func(ctx context.Context) error

Hook is invoked during shutdown. Implementations should respect ctx and return promptly when it's cancelled — the coordinator imposes per-hook timeouts.

type Option

type Option func(*Coordinator)

func WithGraceWindow

func WithGraceWindow(d time.Duration) Option

WithGraceWindow sets the overall grace budget. Hooks running past this are abandoned and Run returns with their timeout error. Default: 30s.

func WithHookTimeout

func WithHookTimeout(d time.Duration) Option

WithHookTimeout sets the per-hook timeout. Default: 10s.

func WithLogger

func WithLogger(logf func(format string, args ...any)) Option

WithLogger wires a logging function called with shutdown lifecycle events. Defaults to a no-op.

func WithSignals

func WithSignals(sig ...os.Signal) Option

WithSignals overrides the signal set that triggers shutdown. Default: SIGINT + SIGTERM.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL