Handle Signal Interrupt in Golang

Would you like your program to do something when the user hits Ctrl + C a.k.a SIGINT?

There will be cases where a program needs to do something before exiting (like writing to files, closing connections etc) especially if the program is long running and the user needs to hit Ctrl + C to exit the program.

For this, you need to handle SIGINT. This is pretty straight forward in golang and all you need is the following function:

func CtrlCHandler() {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("\r- Ctrl+C pressed, exiting")
		DoSomething()
		os.Exit(0)
	}()
}

The function creates a “listener” which runs in a goroutine that will notify the program if it receives an interrupt from the OS.

Example:

package main

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

func main() {

	// Setup Ctrl+C handler
	CtrlCHandler()

    // A loop that never exits
    for {
		fmt.Println("Sleeping for 10s...")
		time.Sleep(10 * time.Second)
	}
}

func CtrlCHandler() {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("\r- Ctrl+C pressed, exiting")
		DoSomething()
		os.Exit(0)
	}()
}

func DoSomething() {
    fmt.Println("Did something before exiting!")
}