You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
31 lines
582 B
31 lines
582 B
package main
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"os/signal"
|
|
)
|
|
|
|
// 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)
|
|
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
|
|
}
|