English | 中文
Providing shutdown callbacks for graceful app shutdown
go get github.com/seacraft/shutdown
github.com/seacraft/shutdown
documentation is available on godoc.
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)
}
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)
}
See LICENSE file in the root of the repository.