-
Notifications
You must be signed in to change notification settings - Fork 88
/
message.go
66 lines (57 loc) · 1.31 KB
/
message.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
package easytcp
import (
"fmt"
"sync"
)
// NewMessage creates a Message pointer.
func NewMessage(id interface{}, data []byte) *Message {
return &Message{
id: id,
data: data,
}
}
// Message is the abstract of inbound and outbound message.
type Message struct {
id interface{}
data []byte
storage map[string]interface{}
mu sync.RWMutex
}
// ID returns the id of current message.
func (m *Message) ID() interface{} {
return m.id
}
// Data returns the data part of current message.
func (m *Message) Data() []byte {
return m.data
}
// Set stores kv pair.
func (m *Message) Set(key string, value interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
if m.storage == nil {
m.storage = make(map[string]interface{})
}
m.storage[key] = value
}
// Get retrieves the value according to the key.
func (m *Message) Get(key string) (value interface{}, exists bool) {
m.mu.RLock()
defer m.mu.RUnlock()
value, exists = m.storage[key]
return
}
// MustGet retrieves the value according to the key.
// Panics if key does not exist.
func (m *Message) MustGet(key string) interface{} {
if v, ok := m.Get(key); ok {
return v
}
panic(fmt.Errorf("key `%s` does not exist", key))
}
// Remove deletes the key from storage.
func (m *Message) Remove(key string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.storage, key)
}