/
message.go
69 lines (56 loc) · 1.15 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
67
68
69
package messages
import (
"encoding/binary"
"github.com/vmihailenco/msgpack"
"math"
"sync"
)
var messageIdLocker = sync.Mutex{}
var messageId = uint32(1)
func NewMessage() *Message {
return &Message{}
}
func NewActionMessage(action ActionInterface) *Message {
m := &Message{
Action: action.Name(),
Value: action,
}
return m
}
type Message struct {
Id uint32
Action string
Value interface{}
}
func (this *Message) Marshal() ([]byte, error) {
data, err := msgpack.Marshal(this.Value)
if err != nil {
return []byte{}, err
}
// id
b := make([]byte, 8)
if this.Id == 0 {
this.Id = this.nextId()
}
binary.BigEndian.PutUint32(b, this.Id)
// action length
b2 := make([]byte, 8)
binary.BigEndian.PutUint32(b2, uint32(len(this.Action)))
b = append(b, b2...)
// data length
b3 := make([]byte, 8)
binary.BigEndian.PutUint32(b3, uint32(len(data)))
b = append(b, b3...)
b = append(b, []byte(this.Action)...)
return append(b, data...), nil
}
func (this *Message) nextId() uint32 {
messageIdLocker.Lock()
defer messageIdLocker.Unlock()
if messageId == math.MaxUint32 {
messageId = 1
} else {
messageId++
}
return messageId
}