forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler_decode.go
62 lines (44 loc) · 1014 Bytes
/
handler_decode.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
package cellnet
import (
"errors"
"reflect"
)
type DecodePacketHandler struct {
}
func (self *DecodePacketHandler) Call(ev *Event) {
var err error
ev.Msg, err = DecodeMessage(ev.MsgID, ev.Data)
r := errToResult(err)
if r != Result_OK {
ev.Msg, _ = DecodeMessage(ev.MsgID, ev.Data)
ev.SetResult(r)
}
}
var defaultDecodePacketHandler = new(DecodePacketHandler)
func StaticDecodePacketHandler() EventHandler {
return defaultDecodePacketHandler
}
var ErrCodecNotFound = errors.New("codec not found")
func DecodeMessage(msgid uint32, data []byte) (interface{}, error) {
meta := MessageMetaByID(msgid)
if meta == nil {
return nil, ErrMessageNotFound
}
if meta.Codec == nil {
return nil, ErrCodecNotFound
}
// 创建消息
msg := reflect.New(meta.Type).Interface()
// 解析消息
err := meta.Codec.Decode(data, msg)
if err != nil {
return nil, err
}
return msg, nil
}
func errToResult(err error) Result {
if err == nil {
return Result_OK
}
return Result_CodecError
}