File tree Expand file tree Collapse file tree 3 files changed +71
-12
lines changed Expand file tree Collapse file tree 3 files changed +71
-12
lines changed Original file line number Diff line number Diff line change 1+ package xcontext
2+
3+ import (
4+ "context"
5+ "time"
6+ )
7+
8+ type doneCtx <- chan struct {}
9+
10+ func (done doneCtx ) Deadline () (deadline time.Time , ok bool ) {
11+ return
12+ }
13+
14+ func (done doneCtx ) Done () <- chan struct {} {
15+ return done
16+ }
17+
18+ func (done doneCtx ) Err () error {
19+ select {
20+ case <- done :
21+ return context .Canceled
22+ default :
23+ return nil
24+ }
25+ }
26+
27+ func (done doneCtx ) Value (key any ) any {
28+ return nil
29+ }
30+
31+ func WithDone (parent context.Context , done <- chan struct {}) (context.Context , context.CancelFunc ) {
32+ ctx , cancel := context .WithCancel (parent )
33+ stop := context .AfterFunc (doneCtx (done ), func () {
34+ cancel ()
35+ })
36+
37+ return ctx , func () {
38+ stop ()
39+ cancel ()
40+ }
41+ }
Original file line number Diff line number Diff line change 1+ package xcontext
2+
3+ import (
4+ "context"
5+ "testing"
6+
7+ "github.com/stretchr/testify/require"
8+ )
9+
10+ func TestWithDone (t * testing.T ) {
11+ t .Run ("CancelParent" , func (t * testing.T ) {
12+ ctx , cancel := context .WithCancel (context .Background ())
13+ done := make (chan struct {})
14+ ctx1 , _ := WithDone (ctx , done )
15+ require .NoError (t , ctx1 .Err ())
16+ cancel ()
17+ require .Error (t , ctx1 .Err ())
18+ })
19+ t .Run ("CloseDone" , func (t * testing.T ) {
20+ ctx , cancel := context .WithCancel (context .Background ())
21+ defer cancel ()
22+ done := make (chan struct {})
23+ ctx1 , cancel1 := WithDone (ctx , done )
24+ require .NoError (t , ctx1 .Err ())
25+ cancel1 ()
26+ require .NoError (t , ctx .Err ())
27+ require .Error (t , ctx1 .Err ())
28+ })
29+ }
Original file line number Diff line number Diff line change @@ -2,20 +2,9 @@ package xcontext
22
33import (
44 "context"
5- "time"
65)
76
8- type valueOnlyContext struct {
9- context.Context //nolint:containedctx
10- }
11-
12- func (valueOnlyContext ) Deadline () (deadline time.Time , ok bool ) { return }
13-
14- func (valueOnlyContext ) Done () <- chan struct {} { return nil }
15-
16- func (valueOnlyContext ) Err () error { return nil }
17-
187// ValueOnly helps to clear parent context from deadlines/cancels
198func ValueOnly (ctx context.Context ) context.Context {
20- return valueOnlyContext { ctx }
9+ return context . WithoutCancel ( ctx )
2110}
You can’t perform that action at this time.
0 commit comments