Signals
Context
Section titled “Context”The os/signal package allows Go programs to receive Unix signals (e.g., SIGINT, SIGTERM). This is used for graceful shutdown.
Example
Section titled “Example”Catch Ctrl+C and print a message before exiting.
Code example
Section titled “Code example”package main
import ( "fmt" "os" "os/signal" "syscall")
func main() { sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
fmt.Println("Waiting for signal...") s := <-sigs fmt.Println("Received signal:", s)}Output (press Ctrl+C)
Section titled “Output (press Ctrl+C)”Waiting for signal...^CReceived signal: interrupt