/
context.go
57 lines (48 loc) · 1.22 KB
/
context.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
52
53
54
55
56
57
package tool
import (
"context"
"os"
"os/signal"
"sync/atomic"
"time"
)
// Context represents cancelable context which also reacts to os.Interrupt signal.
type Context struct {
ctx context.Context
ctxSignalNotifyStop context.CancelFunc
ctxCancel context.CancelFunc
canceled atomic.Bool
}
// NewContext returns new Context based on parent.
func NewContext(parent context.Context) *Context {
ctx, cancel := context.WithCancel(parent)
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
c := &Context{
ctx: ctx,
ctxSignalNotifyStop: stop,
ctxCancel: cancel,
canceled: atomic.Bool{},
}
return c
}
// Cancel context and stops listening.
// It can be called repeatedly and safely from simultaneous goroutines.
func (c *Context) Cancel() {
if c.canceled.CompareAndSwap(false, true) {
c.ctxCancel()
c.ctxSignalNotifyStop()
}
}
func (c *Context) Deadline() (deadline time.Time, ok bool) {
return c.ctx.Deadline()
}
func (c *Context) Done() <-chan struct{} {
return c.ctx.Done()
}
func (c *Context) Err() error {
return c.ctx.Err()
}
func (c *Context) Value(key any) any {
return c.ctx.Value(key)
}
var _ context.Context = (*Context)(nil)