shutdown

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2023 License: Apache-2.0 Imports: 7 Imported by: 0

README

Shutdown Go Report Card Coverage Status PkgGoDev

Shutdown package aims to gracefully shut down a given function with configurable options.

Options

shutdown.New() accepts a collection of shutdown.Options as listed bellow :

  • shutdown.WithContext() pass a parent context.
  • shutdown.WithLogger() pass a custom logger implementing shutdown.Logger.
  • shutdown.WithSignals() configure os.Signal to be triggered as shutdown event
  • shutdown.WithTimeExpiration() set up a timeout so shutdown functions won't hang up the system.

Usage

Any function requiring graceful shutdown shall be registered through Shutdown.Register(). These functions must implement shutdown.Closable which is a func() error type that fit perfectly with io.Closer interface.

os.Interrupt and syscall.SIGTERM are listened by default if no signals configured with shutdown.WithSignals().

No timeout is set by default.

log.Default() is set as default logger.

package main

import (
	"context"
	"log"
	"net/http"

	"github.com/jkuma/shutdown"
)

func main() {
	ctx := context.Background()
	server := &http.Server{}

	httpshut := func() error {
		return server.Shutdown(ctx)
	}

	shut := shutdown.New(shutdown.WithContext(ctx)).Register(httpshut)

	shut.RunGraceful(func() {
		if err := server.ListenAndServe(); err != nil {
			log.Fatal(err)
		}
	})
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Closable

type Closable func() error

type Logger

type Logger interface {
	Println(v ...any)
	Fatalf(format string, v ...any)
}

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithContext

func WithContext(ctx context.Context) Option

WithContext allows to pass a context.

func WithLogger

func WithLogger(l Logger) Option

WithLogger injects a service implementing Logger.

func WithSignals

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

WithSignals listen to given os.Signal as shutdown trigger.

func WithTimeExpiration

func WithTimeExpiration(expr time.Duration) Option

WithTimeExpiration set a timeout for shutdown functions.

type Shutdown

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

func New

func New(opts ...Option) *Shutdown

func (*Shutdown) Register

func (s *Shutdown) Register(c ...Closable) *Shutdown

Register a collection of Closable functions that will be gracefully closed.

func (*Shutdown) RunGraceful

func (s *Shutdown) RunGraceful(fn func())

RunGraceful shutdown of given function.

Jump to

Keyboard shortcuts

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