Skip to content

Latest commit

 

History

History

shutdown

shutdown

import "github.com/induzo/gocom/shutdown"

This package allows you to gracefully shutdown your app.

Index

type Hook

Hook is a shutdown hook that will be called when signal is received.

type Hook struct {
    Name       string
    ShutdownFn func(ctx context.Context) error
}

type Option

Option is the options type to configure Shutdown.

type Option func(*Shutdown)

func WithGracePeriodDuration

func WithGracePeriodDuration(gracePeriodDuration time.Duration) Option

WithGracePeriodDuration sets the grace period for all shutdown hooks to finish running. If not used, the default grace period is 30s.

func WithHooks

func WithHooks(hooks []Hook) Option

WithHooks adds the hooks to be run as part of the graceful shutdown.

type Shutdown

Shutdown provides a way to listen for signals and handle shutdown of an application gracefully.

type Shutdown struct {
    // contains filtered or unexported fields
}
Example

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"log/slog"
	"net/http"
	"syscall"
	"time"

	"github.com/induzo/gocom/shutdown"
)

func main() {
	textHandler := slog.NewTextHandler(io.Discard, nil)
	logger := slog.New(textHandler)

	shutdownHandler := shutdown.New(
		logger,
		shutdown.WithHooks(
			[]shutdown.Hook{
				{
					Name: "do something",
					ShutdownFn: func(ctx context.Context) error {
						return nil
					},
				},
			},
		),
		shutdown.WithGracePeriodDuration(time.Second))

	var srv http.Server

	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("http server listen and serve: %s", err)
		}
	}()

	shutdownHandler.Add("http server", func(ctx context.Context) error {
		if err := srv.Shutdown(ctx); err != nil {
			return fmt.Errorf("http server shutdown: %w", err)
		}

		return nil
	})

	if err := shutdownHandler.Listen(
		context.Background(),
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT); err != nil {
		log.Fatalf("graceful shutdown failed: %s. forcing exit.", err)
	}
}

func New

func New(logger *slog.Logger, opts ...Option) *Shutdown

New returns a new Shutdown with the provided options.

func (*Shutdown) Add

func (s *Shutdown) Add(name string, fn func(ctx context.Context) error)

Add adds a shutdown hook to be run when the signal is received.

func (*Shutdown) Hooks

func (s *Shutdown) Hooks() []Hook

Hooks returns a copy of the shutdown hooks.

func (*Shutdown) Listen

func (s *Shutdown) Listen(ctx context.Context, signals ...os.Signal) error

Listen waits for the signals provided and executes each shutdown hook sequentially in FILO order. It will immediately stop and return once the grace period has passed.

Generated by gomarkdoc