jlelse’s Blog

Thoughts, stories and ideas

go-shutdowner: Simple graceful shutdowns in Go

Published on in 👨‍💻 Dev
Short link: https://b.jlel.se/s/471
Share online Translate

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 (

	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() {


	// CTRL + C or otherwise interrupt the program

	// Wait for shutdowner to finish



$ go run example.go
2021/06/19 08:48:07 Started
^C2021/06/19 08:48:08 Shutdown

Tags: ,

Jan-Lukas Else
Interactions & Comments