-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added
xcontext.WithDone()
+ replaced custom implementation `xcontex…
…t.ValueOnly()` to standard `context.WithoutCancel()`
- Loading branch information
1 parent
7842cf9
commit 0f44d84
Showing
3 changed files
with
69 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package xcontext | ||
|
||
import ( | ||
"context" | ||
"time" | ||
) | ||
|
||
type doneCtx <-chan struct{} | ||
|
||
func (done doneCtx) Deadline() (deadline time.Time, ok bool) { | ||
return | ||
} | ||
|
||
func (done doneCtx) Done() <-chan struct{} { | ||
return done | ||
} | ||
|
||
func (done doneCtx) Err() error { | ||
select { | ||
case <-done: | ||
return context.Canceled | ||
default: | ||
return nil | ||
} | ||
} | ||
|
||
func (d doneCtx) Value(key any) any { | ||
return nil | ||
} | ||
|
||
func WithDone(parent context.Context, done <-chan struct{}) (context.Context, context.CancelFunc) { | ||
ctx, cancel := context.WithCancel(parent) | ||
stop := context.AfterFunc(doneCtx(done), func() { | ||
cancel() | ||
}) | ||
return ctx, func() { | ||
stop() | ||
cancel() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package xcontext | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestWithDone(t *testing.T) { | ||
t.Run("CancelParent", func(t *testing.T) { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
done := make(chan struct{}) | ||
ctx1, _ := WithDone(ctx, done) | ||
require.NoError(t, ctx1.Err()) | ||
cancel() | ||
require.Error(t, ctx1.Err()) | ||
}) | ||
t.Run("CloseDone", func(t *testing.T) { | ||
ctx, _ := context.WithCancel(context.Background()) | ||
done := make(chan struct{}) | ||
ctx1, cancel1 := WithDone(ctx, done) | ||
require.NoError(t, ctx1.Err()) | ||
cancel1() | ||
require.NoError(t, ctx.Err()) | ||
require.Error(t, ctx1.Err()) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters