Help us shape the future of Go! Take the 2026 Go Developer Survey

shutdown

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package shutdown releases an application's resources in order when it stops.

Graceful runs a list of steps - stop the HTTP server, then close the database, for instance - under a single deadline:

stopServer := server.Run()
<-interrupt

err := shutdown.Graceful(ctx, 15*time.Second,
	shutdown.Step(stopServer),
	func(context.Context) error { return conn.Close() },
)

The deadline bounds the whole sequence, so a server that never finishes draining its connections cannot hang the process past the orchestrator's grace period. Keep the timeout below that period (30s by default on Kubernetes). A failing or timed-out step does not stop the sequence: the remaining steps still run and every error is joined into the returned one.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Graceful

func Graceful(ctx context.Context, timeout time.Duration, steps ...Step) error

Graceful runs steps in order, all sharing a single deadline of timeout, so a step that never finishes cannot hang the process. Every step runs even if an earlier one fails or times out, so later resources are still released. The errors of the failing steps are joined; nil is returned when all succeed.

Example

Steps run in the order they are given, all under the same deadline.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/diegodesousas/go-devkit/pkg/shutdown"
)

func main() {
	err := shutdown.Graceful(context.Background(), 5*time.Second,
		func(context.Context) error {
			fmt.Println("http server stopped")
			return nil
		},
		func(context.Context) error {
			fmt.Println("database closed")
			return nil
		},
	)

	fmt.Println("error:", err)

}
Output:
http server stopped
database closed
error: <nil>
Example (FailingStep)

A failing step does not prevent the next ones from running; its error is returned once every step ran.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/diegodesousas/go-devkit/pkg/shutdown"
	"github.com/pkg/errors"
)

func main() {
	err := shutdown.Graceful(context.Background(), 5*time.Second,
		func(context.Context) error {
			return errors.New("http server did not stop")
		},
		func(context.Context) error {
			fmt.Println("database closed")
			return nil
		},
	)

	fmt.Println("error:", err)

}
Output:
database closed
error: http server did not stop

Types

type Step

type Step func(ctx context.Context) error

Step releases one resource, such as the function returned by httpserver.Server.Run or a database connection's Close.

Jump to

Keyboard shortcuts

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