Go by Example

Signals

signal.NotifyContext ties a context to SIGINT/SIGTERM - cancel it to propagate graceful shutdown to every goroutine that respects context cancellation.

An operating-system signal notifies a process about an external event. signal.NotifyContext connects selected signals to context cancellation.

When the context is cancelled, the application can stop work that observes it. Call the returned stop function to release signal handling.

package main
 
import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "syscall"
)
 
func main() {
    ctx, stop := signal.NotifyContext(
        context.Background(), os.Interrupt, syscall.SIGTERM,
    )
    defer stop()
 
    <-ctx.Done()
    fmt.Println("shutdown requested")
}

In production

Container platforms commonly send SIGTERM before stopping a service. Pass the signal context to workers and use a bounded graceful-shutdown step for servers. Cancellation only helps components that check the context; it does not forcibly stop goroutines.

Enjoyed this? Get more software craft delivered to your inbox.