Skip to content

Commit 37009ea

Browse files
committed
(BC) closer.New now returns notifiable context
1 parent 47334f5 commit 37009ea

2 files changed

Lines changed: 11 additions & 8 deletions

File tree

closer/closer.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ type closer struct {
3535
once sync.Once
3636
}
3737

38-
var global = New(context.Background())
38+
var _, global = New(context.Background())
3939

4040
// SetContext sets context into the global Closer.
4141
func SetContext(ctx context.Context) {
@@ -62,28 +62,31 @@ func CloseAll() {
6262
global.CloseAll()
6363
}
6464

65-
// New returns base Closer implementation.
65+
// New returns signal notifiable Context and base Closer implementation.
6666
//
6767
// If signals specified, then close functions will trigger when any arrives.
68-
func New(ctx context.Context, signals ...os.Signal) *closer {
68+
func New(ctx context.Context, signals ...os.Signal) (context.Context, *closer) {
6969
c := &closer{done: make(chan struct{})}
7070
if ctx == nil {
7171
panic("cannot create closer with nil context")
7272
}
7373
c.ctx.Store(&ctx)
7474

75+
var cancel context.CancelFunc
76+
if len(signals) > 0 {
77+
ctx, cancel = signal.NotifyContext(ctx, signals...)
78+
}
79+
7580
go func() {
76-
if len(signals) > 0 {
77-
var cancel context.CancelFunc
78-
ctx, cancel = signal.NotifyContext(ctx, signals...)
81+
if cancel != nil {
7982
defer cancel()
8083
}
8184

8285
<-ctx.Done()
8386
c.CloseAll() //nolint:contextcheck
8487
}()
8588

86-
return c
89+
return ctx, c
8790
}
8891

8992
func (c *closer) SetContext(ctx context.Context) {

closer/closer_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func TestCloser(t *testing.T) {
4343
goleak.VerifyNone(t, goleak.IgnoreCurrent())
4444

4545
ctx, cancel := context.WithCancel(context.Background())
46-
c := New(ctx)
46+
_, c := New(ctx)
4747

4848
var cnt atomic.Uint32
4949
c.Add(func(context.Context) error {

0 commit comments

Comments
 (0)