forked from panjf2000/gnet
/
msg.go
104 lines (88 loc) · 1.75 KB
/
msg.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
98
99
100
101
102
103
104
package socker
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
)
type (
Data struct {
gjson.Result
}
Reply struct {
Async bool
Status Action
Body interface{}
}
Message struct {
length int
bytes []byte
bodyLength int
bodyBytes []byte
async bool
Api string `json:"api"`
Body interface{} `json:"body,omitempty"`
}
)
func (m *Message) BodyBytes() []byte {
b, _ := json.Marshal(m.Body)
return b
}
func (m *Message) BodyLength() int {
return m.bodyLength
}
func (m *Message) BodyStringify() string {
return string(m.bodyBytes)
}
func NewMessage(api string, data interface{}) *Message {
m := &Message{
Api: api,
Body: data,
}
m.bytes = m.Bytes()
m.length = len(m.bytes)
m.bodyBytes = m.BodyBytes()
m.bodyLength = len(m.bodyBytes)
return m
}
func (m *Message) reset(async bool, body interface{}) {
m.async = async
m.Body = body
m.bytes = m.Bytes()
m.length = len(m.bytes)
m.bodyBytes = m.BodyBytes()
m.bodyLength = len(m.bodyBytes)
}
func (m *Message) out() []byte {
return MergeBytes(IntToBytes(m.length), m.bytes)
}
func (m *Message) Async() bool {
return m.async
}
func (m *Message) Parse(b []byte) error {
m.bytes = b
m.length = len(b)
decoder := json.NewDecoder(bytes.NewReader(b))
decoder.UseNumber()
if err := decoder.Decode(&m); err != nil {
return err
}
m.bodyBytes = m.BodyBytes()
m.bodyLength = len(m.bodyBytes)
return nil
}
func (m *Message) Bytes() []byte {
b, _ := json.Marshal(m)
return b
}
func (m *Message) Stringify() string {
return string(m.bytes)
}
func (m *Message) GJson() gjson.Result {
return gjson.ParseBytes(m.bodyBytes)
}
func (m *Message) ToData() Data {
return Data{m.GJson()}
}
func (m *Message) Length() int {
return m.length
}