-
Notifications
You must be signed in to change notification settings - Fork 0
/
property.go
91 lines (74 loc) · 1.54 KB
/
property.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package peer
import (
"reflect"
"sync"
)
type ctx struct {
key interface{}
value interface{}
}
// 上下文记录,绑定用户自定义数据
type CoreContextSet struct {
ctxes []ctx
ctxesGuard sync.RWMutex
}
func (self *CoreContextSet) FetchContext(key, valuePtr interface{}) bool {
pv, ok := self.GetContext(key)
if !ok {
return false
}
switch rawValue := valuePtr.(type) {
case *string:
*rawValue = pv.(string)
case *int:
*rawValue = pv.(int)
case *int32:
*rawValue = pv.(int32)
case *int64:
*rawValue = pv.(int64)
case *uint:
*rawValue = pv.(uint)
case *uint32:
*rawValue = pv.(uint32)
case *uint64:
*rawValue = pv.(uint64)
case *bool:
*rawValue = pv.(bool)
case *float32:
*rawValue = pv.(float32)
case *float64:
*rawValue = pv.(float64)
case *[]byte:
*rawValue = pv.([]byte)
default:
v := reflect.Indirect(reflect.ValueOf(valuePtr))
// 避免call of reflect.Value.Set on zero Value
if pv == nil {
v.Set(reflect.Zero(v.Type()))
} else {
v.Set(reflect.ValueOf(pv))
}
}
return true
}
func (self *CoreContextSet) GetContext(key interface{}) (interface{}, bool) {
self.ctxesGuard.RLock()
defer self.ctxesGuard.RUnlock()
for _, t := range self.ctxes {
if t.key == key {
return t.value, true
}
}
return nil, false
}
func (self *CoreContextSet) SetContext(key, v interface{}) {
self.ctxesGuard.Lock()
defer self.ctxesGuard.Unlock()
for i, t := range self.ctxes {
if t.key == key {
self.ctxes[i] = ctx{key, v}
return
}
}
self.ctxes = append(self.ctxes, ctx{key, v})
}