-
Notifications
You must be signed in to change notification settings - Fork 4
/
detach.go
51 lines (44 loc) · 1.17 KB
/
detach.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package onecontext
import (
"context"
"time"
)
// DetachedContext holds the logic to detach a cancellation signal from a context.
type DetachedContext struct {
ctx context.Context
ch chan struct{}
cancel func()
}
// Detach detaches the cancellation signal from a context.
func Detach(ctx context.Context) (*DetachedContext, func()) {
ch := make(chan struct{})
cancel := func() {
close(ch)
}
return &DetachedContext{
ctx: ctx,
ch: ch,
cancel: cancel,
}, cancel
}
// Deadline returns a nil deadline.
func (c *DetachedContext) Deadline() (time.Time, bool) {
return time.Time{}, false
}
// Done returns a cancellation signal that expires only when the context is canceled from the cancel function returned in Detach.
func (c *DetachedContext) Done() <-chan struct{} {
return c.ch
}
// Err returns an error if the context is canceled from the cancel function returned in Detach.
func (c *DetachedContext) Err() error {
select {
case <-c.Done():
return ErrCanceled
default:
return nil
}
}
// Value returns the value associated with the key from the original context.
func (c *DetachedContext) Value(key interface{}) interface{} {
return c.ctx.Value(key)
}