To catch and handle signals gracefully using runtime.Notify() in Go, you need to follow these steps:
import (
"os"
"os/signal"
"syscall"
)
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-quit
// Custom handling of the signal
// ...
}()
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.