Skip to content

Instantly share code, notes, and snippets.

@LinkTsang
Forked from matejb/sigterm_context.go
Created February 24, 2023 08:02
Show Gist options
  • Save LinkTsang/e3a51f31549dde07d3d39926c7b3bbcb to your computer and use it in GitHub Desktop.
Save LinkTsang/e3a51f31549dde07d3d39926c7b3bbcb to your computer and use it in GitHub Desktop.

Revisions

  1. @matejb matejb created this gist May 20, 2017.
    16 changes: 16 additions & 0 deletions sigterm_context.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    func contextWithSigterm(ctx context.Context) context.Context {
    ctxWithCancel, cancel := context.WithCancel(ctx)
    go func() {
    defer cancel()

    signalCh := make(chan os.Signal, 1)
    signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)

    select {
    case <-signalCh:
    case <-ctx.Done():
    }
    }()

    return ctxWithCancel
    }