Jan-Lukas Else

Thoughts of an IT expert

go-shutdowner: Simple graceful shutdowns in Go

Published on in 👨‍💻 Dev
Short link: https://b.jlel.se/s/471
⚠️ This entry is already over one year old. It may no longer be up to date. Opinions may have changed.

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

Tags: ,

Jan-Lukas Else
Interactions & Comments