diff --git a/grace/grace.go b/grace/grace.go index d7b853f..56b9f1c 100644 --- a/grace/grace.go +++ b/grace/grace.go @@ -1,30 +1,10 @@ package grace import ( - "context" - "os" - "os/signal" - "syscall" - "github.com/im-kulikov/helium/module" - "go.uber.org/zap" ) // Module graceful context var Module = module.Module{ {Constructor: NewGracefulContext}, } - -// NewGracefulContext returns graceful context -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 - l.Info("received signal", - zap.String("signal", sig.String())) - cancel() - }() - return ctx -} diff --git a/grace/grace_go1.15.go b/grace/grace_go1.15.go new file mode 100644 index 0000000..9335832 --- /dev/null +++ b/grace/grace_go1.15.go @@ -0,0 +1,26 @@ +// +build !go1.16 + +package grace + +import ( + "context" + "os" + "os/signal" + "syscall" + + "go.uber.org/zap" +) + +// NewGracefulContext returns graceful context +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 + l.Info("received stop signal", + zap.String("signal", sig.String())) + cancel() + }() + return ctx +} diff --git a/grace/grace_go1.16.go b/grace/grace_go1.16.go new file mode 100644 index 0000000..865c2c7 --- /dev/null +++ b/grace/grace_go1.16.go @@ -0,0 +1,24 @@ +// +build go1.16 + +package grace + +import ( + "context" + "os/signal" + "syscall" + + "go.uber.org/zap" +) + +// NewGracefulContext returns graceful context +func NewGracefulContext(l *zap.Logger) context.Context { + ctx, _ := signal.NotifyContext(context.Background(), + syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP) + + go func() { + <-ctx.Done() + l.Info("receive stop signal") + }() + + return ctx +} diff --git a/grace/grace_test.go b/grace/grace_test.go index 160399d..1c52839 100644 --- a/grace/grace_test.go +++ b/grace/grace_test.go @@ -7,24 +7,22 @@ import ( "time" "github.com/stretchr/testify/assert" - "go.uber.org/zap" + "go.uber.org/zap/zaptest" ) func TestGrace(t *testing.T) { - var ( - log = zap.L() - ctx = NewGracefulContext(log) - ) - - // waiting to run the goroutine and channel of signals - <-time.Tick(100 * time.Millisecond) - signals := []syscall.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP} for i := range signals { sig := signals[i] t.Run(fmt.Sprintf("should cancel context on %s signal", sig), func(t *testing.T) { is := assert.New(t) + log := zaptest.NewLogger(t) + ctx := NewGracefulContext(log) + + // waiting to run the goroutine and channel of signals + <-time.After(time.Millisecond) + err := syscall.Kill(syscall.Getpid(), sig) is.NoError(err)