Skip to content

Easy How to Catch Signals and Gracefully Shutdown in Golang!

Is there a chance to catch the termination (or interruption) signals and do some tasks before quitting the app in golang?

YES!

Just use this fantastic code snippet:

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {

	// Run the termination task in a goroutine
	go terminationSetup()

	// Start your normal service
	for {
		fmt.Println("Normal service is running!")
		time.Sleep(2 * time.Second)
	}

	// Try to send intruption signals with your keyboard: CTRL + C
}

func terminationSetup() {
	// sigChan channel to catch signal notifications.
	sigChan := make(chan os.Signal, 1)

	// Catch the signal and pass it to sigChan channel.
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)

	// Wait for the incoming signal
	sig := <-sigChan

	fmt.Println("I recived", sig, "the signal!")

	time.Sleep(3 * time.Second)

	fmt.Println("After 3 seconds wait!")

	// Do something here before exit, for example:
	// - Stop accepting new connection!
	// - Close db connections
	// - Write a log file

	os.Exit(1)
}

Leave a Reply

Your email address will not be published. Required fields are marked *