Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrasilnikov committed Dec 3, 2017
0 parents commit 2acb61e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Grace pkg

Package with single function for create base context which will be canceled on signals:
`SIGINT`, `SIGTERM`, `SIGHUP`.

## Example

```go
package main

import (
"context"

"github.com/chapsuk/grace"
)

func main() {
ctx := grace.ShutdownContext(context.Background())
<-ctx.Done()
// do graceful shutdown after context was canceled
}
```
21 changes: 21 additions & 0 deletions shutdown.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package grace

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

// ShutdownContext returns child context from passed context which will be canceled
// on incoming signals: SIGINT, SIGTERM, SIGHUP
func ShutdownContext(c context.Context) context.Context {
ctx, cancel := context.WithCancel(c)
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
<-ch
cancel()
}()
return ctx
}

0 comments on commit 2acb61e

Please sign in to comment.