forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket.go
51 lines (36 loc) · 861 Bytes
/
packet.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
package cellnet
import (
"reflect"
"github.com/golang/protobuf/proto"
)
// 普通封包
type Packet struct {
MsgID uint32 // 消息ID
Data []byte
}
func (self Packet) ContextID() uint32 {
return self.MsgID
}
// 消息到封包
func BuildPacket(data interface{}) (*Packet, *MessageMeta) {
msg := data.(proto.Message)
rawdata, err := proto.Marshal(msg)
if err != nil {
log.Errorln(err)
}
meta := MessageMetaByName(MessageFullName(reflect.TypeOf(msg)))
return &Packet{
MsgID: uint32(meta.ID),
Data: rawdata,
}, meta
}
// 封包到消息
func ParsePacket(pkt *Packet, msgType reflect.Type) (interface{}, error) {
// msgType 为ptr类型, new时需要非ptr型
rawMsg := reflect.New(msgType.Elem()).Interface()
err := proto.Unmarshal(pkt.Data, rawMsg.(proto.Message))
if err != nil {
return nil, err
}
return rawMsg, nil
}