Skip to content

seacraft/shutdown

Repository files navigation

shutdown

workflow ci PkgGoDev Go Report Card golangci badge release License Releases

English | 中文

Providing shutdown callbacks for graceful app shutdown

Installation

go get github.com/seacraft/shutdown

Documentation

github.com/seacraft/shutdown documentation is available on godoc.

Example - POSIX signals

Graceful shutdown will listen for posix SIGINT and SIGTERM signals. When they are received it will run all callbacks in separate go routines. When callbacks return, the application will exit with os.Exit(0)

package main

import (
	"fmt"
	"time"

	"github.com/seacraft/shutdown"
)

func main() {
	// initialize shutdown
	gs := shutdown.New()

	// add posix shutdown manager
	gs.AddShutdownManager(shutdown.NewPosixSignalManager())

	// add your tasks that implement ShutdownCallback
	gs.AddShutdownCallback(shutdown.ShutdownFunc(func(string) error {
		fmt.Println("Shutdown callback start")
		time.Sleep(time.Second)
		fmt.Println("Shutdown callback finished")
		return nil
	}))

	// start shutdown managers
	if err := gs.Start(); err != nil {
		fmt.Println("Start:", err)
		return
	}

	// do other stuff
	time.Sleep(time.Hour)
}

Example - posix signals with error handler

The same as above, except now we set an ErrorHandler that prints the error returned from ShutdownCallback.

package main

import (
	"fmt"
	"time"
	"errors"

	"github.com/seacraft/shutdown"
)

func main() {
	// initialize shutdown
	gs := shutdown.New()

	// add posix shutdown manager
	gs.AddShutdownManager(shutdown.NewPosixSignalManager())

	// set error handler
	gs.SetErrorHandler(shutdown.ErrorFunc(func(err error) {
		fmt.Println("Error:", err)
	}))

	// add your tasks that implement ShutdownCallback
	gs.AddShutdownCallback(shutdown.ShutdownFunc(func(string) error {
		fmt.Println("Shutdown callback start")
		time.Sleep(time.Second)
		fmt.Println("Shutdown callback finished")
		return errors.New("my-error")
	}))

	// start shutdown managers
	if err := gs.Start(); err != nil {
		fmt.Println("Start:", err)
		return
	}

	// do other stuff
	time.Sleep(time.Hour)
}

Licence

See LICENSE file in the root of the repository.