-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
86 lines (71 loc) · 1.8 KB
/
util.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
package fnet
import (
"os"
"reflect"
"github.com/fanjq99/glog"
)
var logicFunc MessageFunc
// RegisterMessageFunction call outside
func RegisterMessageFunction(f MessageFunc) {
logicFunc = f
}
func DecodeMessage(s ISession, data []byte) {
message := new(Message)
err := message.Decode(data)
if err != nil {
glog.Errorln("message decode error:", err)
} else {
if logicFunc == nil {
panic("not register message function")
os.Exit(1)
}
logicFunc(s, message)
}
}
func ReplyMessage(header *Message, msg interface{}, status uint8) []byte {
serializeType := SerializeType(header.SerializeType)
if serializeType != ProtoBuffer && serializeType != JSON {
glog.Errorln("serializeType not support", header.SerializeType)
return nil
}
data, err := Codecs[serializeType].Encode(msg)
if err != nil {
glog.Errorln(err)
return nil
}
rType := reflect.TypeOf(msg).Elem()
meta := MessageMetaByType(rType)
if meta == nil {
glog.Errorln("can not find message", rType)
return nil
}
message := new(Message)
message.MsgId = meta.ID
message.Index = header.Index
message.SerializeType = header.SerializeType
message.MessageType = uint8(Response)
message.Status = status
message.Data = data
return message.Encode()
}
func RequestMessage(msg interface{}, status, serializeType uint8, indexID uint32) []byte {
data, err := Codecs[SerializeType(serializeType)].Encode(msg)
if err != nil {
glog.Errorln(err)
return nil
}
rType := reflect.TypeOf(msg).Elem()
meta := MessageMetaByType(rType)
if meta == nil {
glog.Errorln("can not find message", rType)
return nil
}
message := new(Message)
message.MsgId = meta.ID
message.Index = indexID
message.SerializeType = serializeType
message.MessageType = uint8(Request)
message.Status = status
message.Data = data
return message.Encode()
}