forked from devfeel/dotweb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
97 lines (85 loc) · 1.87 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package core
import (
"fmt"
"sync"
)
//自带锁,并发安全的Map
type ItemContext struct {
contextMap map[string]interface{}
*sync.RWMutex
}
func NewItemContext() *ItemContext {
return &ItemContext{
contextMap: make(map[string]interface{}),
RWMutex: new(sync.RWMutex),
}
}
/*
* 以key、value置入AppContext
*/
func (ctx *ItemContext) Set(key string, value interface{}) error {
ctx.Lock()
ctx.contextMap[key] = value
ctx.Unlock()
return nil
}
/*
* 读取指定key在AppContext中的内容
*/
func (ctx *ItemContext) Get(key string) (value interface{}, exists bool) {
ctx.RLock()
value, exists = ctx.contextMap[key]
ctx.RUnlock()
return value, exists
}
//remove item by gived key
//if not exists key, do nothing...
func (ctx *ItemContext) Remove(key string) {
ctx.Lock()
delete(ctx.contextMap, key)
ctx.Unlock()
}
//get item by gived key, and remove it
//only can be read once, it will be locked
func (ctx *ItemContext) Once(key string) (value interface{}, exists bool) {
ctx.Lock()
defer ctx.Unlock()
value, exists = ctx.contextMap[key]
if exists {
delete(ctx.contextMap, key)
}
return value, exists
}
/*
* 读取指定key在AppContext中的内容,以string格式输出
*/
func (ctx *ItemContext) GetString(key string) string {
value, exists := ctx.Get(key)
if !exists {
return ""
}
return fmt.Sprint(value)
}
/*
* 读取指定key在AppContext中的内容,以int格式输出
*/
func (ctx *ItemContext) GetInt(key string) int {
value, exists := ctx.Get(key)
if !exists {
return 0
}
return value.(int)
}
//check exists key
func (ctx *ItemContext) Exists(key string) bool {
_, exists := ctx.contextMap[key]
return exists
}
//get current map, returns map[string]interface{}
func (ctx *ItemContext) GetCurrentMap() map[string]interface{} {
return ctx.contextMap
}
//get context length
func (ctx *ItemContext) Len() int {
return len(ctx.contextMap)
}