-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
77 lines (68 loc) · 1.85 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package letsgo
import (
"context"
"errors"
"time"
)
//ContextSet 结构体
type contextOne struct {
CTX context.Context
CTXCancelFunc context.CancelFunc
}
type contextSet map[string]contextOne
//newContextSet 返回一个ContextSet结构体指针
func newContextSet() contextSet {
cs := make(contextSet, 0)
return cs
}
//新建一个ctx
func (ct contextSet) New(ctxtype string, ctxname string, parentname string, timeout time.Duration) (context.Context, context.CancelFunc, error) {
//存在同名
if _, ok := ct[ctxname]; ok {
return nil, nil, errors.New("[error]contextSet New ctxname exists!" + ctxname)
}
var parent context.Context
if parentname == "" {
parent = context.Background()
} else {
var err error
parent, _, err = ct.Get(ctxname)
if err != nil {
return nil, nil, errors.New("[error]contextSet New parentname err:" + parentname + " " + err.Error())
}
}
co := contextOne{}
switch ctxtype {
case "withcancel":
co.CTX, co.CTXCancelFunc = context.WithCancel(parent)
case "withtimeout":
co.CTX, co.CTXCancelFunc = context.WithTimeout(parent, timeout)
default:
return nil, nil, errors.New("[error]contextSet New ctxtype not support:" + ctxtype)
}
ct[ctxname] = co
return co.CTX, co.CTXCancelFunc, nil
}
//获取一个ctx
func (ct contextSet) Get(ctxname string) (context.Context, context.CancelFunc, error) {
if _, ok := ct[ctxname]; !ok {
return nil, nil, errors.New("[error]contextSet Get none-exists ctxname:" + ctxname)
}
gt := ct[ctxname]
return gt.CTX, gt.CTXCancelFunc, nil
}
//删除一个ctx
func (ct contextSet) Remove(ctxname string) error {
if _, ok := ct[ctxname]; !ok {
return errors.New("[error]contextSet Remove none-exists ctxname:" + ctxname)
}
delete(ct, ctxname)
return nil
}
//依次cancel所有ctx
func (ct contextSet) CancelAll() {
for _, ctxo := range ct {
ctxo.CTXCancelFunc()
}
return
}