os/signal

Guided tour · CLI & Runtime · pkg.go.dev →

Receive OS signals (SIGINT, SIGTERM, etc.) via a channel or context.

NotifyContext — the modern idiom

Graceful shutdown

Cancels ctx when the first matching signal arrives. Call stop() to restore default handling. Pairs perfectly with http.Server.Shutdown.

ctx, stop := signal.NotifyContext(context.Background(),
    os.Interrupt, syscall.SIGTERM)
defer stop()

go srv.ListenAndServe()
<-ctx.Done()

shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)

Notify — raw channel version

signal.Notify

Buffered channel of size 1 is the classic pattern — if signals arrive faster than you read, the oldest queued one wins.

ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)

<-ch
fmt.Println("bye")

Stop — unregister

signal.Stop(ch)   // ch will no longer receive signals