-
Notifications
You must be signed in to change notification settings - Fork 1
/
context_check.go
65 lines (55 loc) · 1.17 KB
/
context_check.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
58
59
60
61
62
63
64
65
package checks
import (
"context"
"runtime"
"sync/atomic"
)
type contextCheck struct {
name string
terminated uint32 // TODO: When the minimal supported base go version is 1.19, use atomic.Bool
ctx context.Context
Error error
}
func CheckContextStatus(ctx context.Context, name ...string) error {
check := NewContextCheck(ctx, name...)
return check.checkstatus()
}
func NewContextCheck(ctx context.Context, name ...string) *contextCheck {
if len(name) > 1 {
panic("context check does only accept one name")
}
if ctx == nil {
panic("context check needs a context")
}
contextName := "Unknown"
if len(name) == 1 {
contextName = name[0]
} else {
pc, _, _, ok := runtime.Caller(1)
details := runtime.FuncForPC(pc)
if ok && details != nil {
contextName = details.Name()
}
}
c := contextCheck{
name: contextName,
ctx: ctx,
Error: nil,
}
go func() {
<-ctx.Done()
atomic.StoreUint32(&c.terminated, 1)
}()
return &c
}
func (c *contextCheck) checkstatus() error {
v := atomic.LoadUint32(&c.terminated)
if v == 1 {
c.Error = c.ctx.Err()
return c.Error
}
return nil
}
func (c *contextCheck) Name() string {
return c.name
}