How to catch and handle signals (e.g., SIGINT, SIGTERM) gracefully using runtime.Notify()?

To catch and handle signals gracefully using runtime.Notify() in Go, you need to follow these steps:

  1. Import the necessary packages:
import ( "os" "os/signal" "syscall" )
  1. Create a channel to receive the signals:
quit := make(chan os.Signal, 1)
  1. Register the signals you want to handle:
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  1. Start a goroutine to listen for the signal:
go func() { sig := <-quit // Custom handling of the signal // ... }()
  1. Perform any necessary cleanup or shutdown tasks in the goroutine to handle the signal gracefully.

Here's an example illustrating the complete process:

package main import ( "fmt" "os" "os/signal" "syscall" "time" ) func main() { quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) go func() { sig := <-quit fmt.Printf("\nSignal %s received. Gracefully shutting down...\n", sig) // Custom handling of the signal time.Sleep(2 * time.Second) // Simulating cleanup or shutdown tasks os.Exit(0) }() fmt.Println("Waiting for signals...") <-make(chan struct{}) // Blocking main goroutine indefinitely }

In this example, we catch the SIGINT and SIGTERM signals, perform custom handling inside the goroutine, and gracefully shut down the application after a simulated cleanup or shutdown process.