-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
mkrasilnikov
committed
Dec 3, 2017
0 parents
commit 2acb61e
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |