2020-07-24 13:54:03 +00:00
|
|
|
package grace
|
2020-07-10 14:17:51 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-08-21 11:32:03 +00:00
|
|
|
"fmt"
|
2020-07-10 14:17:51 +00:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
2020-07-24 13:54:03 +00:00
|
|
|
// NewGracefulContext returns grace context that cancelled by sigint,
|
|
|
|
// sigterm and sighup.
|
2020-07-10 14:17:51 +00:00
|
|
|
func NewGracefulContext(l *zap.Logger) context.Context {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
ch := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
|
|
|
|
sig := <-ch
|
2020-08-21 11:32:03 +00:00
|
|
|
if l != nil {
|
|
|
|
l.Info("received signal",
|
|
|
|
zap.String("signal", sig.String()))
|
|
|
|
} else {
|
|
|
|
fmt.Printf("received signal %s\n", sig)
|
|
|
|
}
|
2020-07-10 14:17:51 +00:00
|
|
|
cancel()
|
|
|
|
}()
|
|
|
|
|
|
|
|
return ctx
|
|
|
|
}
|