Go

Signal Handling with signal.NotifyContext

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Go 1.16+ `signal.NotifyContext` returns a context that's canceled on the listed signals. Cleaner than the legacy `signal.Notify(channel)` dance for graceful shutdown.
Go
Raw
package main

import (
    "context"
    "fmt"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(),
        syscall.SIGINT, syscall.SIGTERM)
    defer stop()                                  // restore default handlers

    fmt.Println("running — press Ctrl-C to stop")
    select {
    case <-time.After(60 * time.Second):
        fmt.Println("done by timeout")
    case <-ctx.Done():
        fmt.Println("got signal:", ctx.Err())
        // graceful shutdown logic here
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.