-
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
Showing
6 changed files
with
177 additions
and
79 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,33 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"os" | ||
"os/signal" | ||
) | ||
|
||
/////////////////////////////////////////////////////////////////////////////// | ||
// PUBLIC METHODS | ||
|
||
// ContextForSignal returns a context object which is cancelled when a signal | ||
// is received. It returns nil if no signal parameter is provided | ||
func ContextForSignal(signals ...os.Signal) context.Context { | ||
if len(signals) == 0 { | ||
return nil | ||
} | ||
|
||
ch := make(chan os.Signal, 1) | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
|
||
// Send message on channel when signal received | ||
signal.Notify(ch, signals...) | ||
|
||
// When any signal received, call cancel | ||
go func() { | ||
<-ch | ||
cancel() | ||
}() | ||
|
||
// Return success | ||
return ctx | ||
} |
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
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
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
Oops, something went wrong.