shutdown

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 7 Imported by: 0

README

GoDoc

shutdown

Utility library to handle daemons

Usage

import (
    "net"

    "github.com/KarpelesLab/shutdown"
)

func main() {
    shutdown.SetupSignals()

    // do the things you want to do
    go launchHttp()

    shutdown.Wait()
}

func launchHttp() {
    l, err := net.Listen("tcp", ":80")
    if err != nil {
        shutdown.Fatalf("failed to listen for the http server: %w", err)
        return
    }

    // cleanup of opened listen socket
    shutdown.Defer(func() {
        l.Close()
    })
    // ...
}

Documentation

Overview

Package shutdown provides utilities for graceful application shutdown handling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Defer

func Defer(f func())

Defer registers the given function to be run upon program termination. Functions registered with Defer will be executed in LIFO (Last In, First Out) order when shutdown is triggered.

func Fatalf

func Fatalf(format string, args ...any)

Fatalf reports a fatal error that will trigger shutdown. It accepts format string with arguments similar to fmt.Errorf. It is possible to wrap errors using %w formatting directive.

func Go added in v1.0.4

func Go(funcs ...func() error)

Go runs the provided function(s) in background goroutines. If any of these functions return a non-nil error, it will be handled as a fatal error and cause shutdown to trigger as if Fatalf was called. This is useful for starting background tasks that should cause the application to shut down gracefully if they encounter an error.

func SetupSignals

func SetupSignals()

SetupSignals sets up signal handlers for graceful shutdown. It listens for interruptions (Ctrl-C/SIGINT or SIGTERM), and triggers a shutdown when a signal is received. If a second signal is sent (indicating shutdown is taking too long), this will force termination by calling os.Exit(1). This function should be called early in your application's main function.

func Shutdown

func Shutdown()

Shutdown will trigger the normal shutdown of the program. It can be called multiple times safely as it uses sync.Once internally.

func Wait

func Wait()

Wait blocks until shutdown is triggered, either by calling Shutdown(), receiving a termination signal (if SetupSignals was called), or if an error is sent via Fatalf. After the shutdown is triggered, this function runs all cleanup functions registered with Defer(). This function should be called as the last function in main().

Types

This section is empty.

Jump to

Keyboard shortcuts

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