go-shutdowner: Simple graceful shutdowns in Go
source link: https://jlelse.blog/dev/go-shutdowner
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
go-shutdowner: Simple graceful shutdowns in Go
As I already mentioned, I’m trying to modularize parts of GoBlog to make the code more organized and to be able to test it better (thanks to the tests, I always notice small bugs that I can then correct).
One of these modules, which I even decided to extract as a separate library, contains methods so that I can stop the HTTP servers or close the database connection when the program ends, also called a graceful shutdown.
The library allows this code (100% covered with tests 🤓) to be used in other applications as well. The usage is quite simple. Here is the sample code from the repository:
package main
import (
"log"
goshutdowner "git.jlel.se/jlelse/go-shutdowner"
)
func main() {
// Declare shutdowner
var sd goshutdowner.Shutdowner
// Add a function to execute on shutdown
sd.Add(func() {
log.Println("Shutdown")
})
log.Println("Started")
// CTRL + C or otherwise interrupt the program
// Wait for shutdowner to finish
sd.Wait()
}
Output:
$ go run example.go
2021/06/19 08:48:07 Started
^C2021/06/19 08:48:08 Shutdown
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK