trap

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2021 License: MIT Imports: 6 Imported by: 4

README

trap

Go package for returning a root context for graceful exits

Example

This should typically be used in main. Its context method can be used to return a context that is cancelled when an OS signal is received.

func main() {
	ctx := trap.Context()

	db, err := open(ctx, "...")
	if err != nil {
		log.Fatalf("open: %s", err)
	}

	go work(db)
	<-ctx.Done()
	db.Close()

	log.Println("done :)")
}

Documentation

Overview

Package trap returns a root context for graceful exits.

The package is typically used in main, its context method can be used to return a context that is cancelled when an os signal is received.

func main() {
	ctx := trap.Context()

	db, err := open(ctx, "...")
	if err != nil {
		log.Fatalf("open: %s", err)
	}

	go work(db)
	<-ctx.Done()
	db.Close()

	log.Println("done :)")
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// Timeout is a graceful exit timeout.
	//
	// When reached, `Context()` will call os.Exit(1)
	// and exit the program abruptly.
	//
	// If <= 0, Context() is is ignored.
	Timeout = 1 * time.Minute

	// ForceExit causes trap to exit abruptly
	// on a second signal.
	//
	// When false, a second signal will do nothing.
	ForceExit = true

	// Signals are the signals the package will
	// listen on.
	Signals = []os.Signal{
		os.Interrupt,
		syscall.SIGTERM,
		syscall.SIGQUIT,
	}

	// Printf is the logging function to use.
	//
	// Uses the global logger by default.
	Printf = log.Printf
)

Functions

func Context

func Context() context.Context

Context returns a new context.

The method listens for os signals that are listed in the Signals variable and cancels the returned context when a signal is received.

Once the context is canceled, the method will listen on for more signals, if one is received and ForceExit is true it will force exit with exit code 1.

When Timeout > 0, the method will forcefully exit when the timeout is reached.

Types

This section is empty.

Jump to

Keyboard shortcuts

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