Ai
1 Star 0 Fork 0

nggs/micro

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
protocol.go 1.86 KB
一键复制 编辑 原始数据 按行查看 历史
李文建 提交于 2020-04-05 00:11 +08:00 . 整合其他模块代码
package protocol_v2
import (
"encoding/binary"
"fmt"
p "gitee.com/nggs/network/protocol"
)
const (
PH = 0
)
type IProtocol interface {
IMessageFactoryManager
Encode(i IMessage) ([]byte, error)
Decode(data []byte) (IMessage, error)
}
type protocol struct {
IMessageFactoryManager
allocator p.IAllocator
encryptor p.IEncryptor
decryptor p.IDecryptor
}
func New(allocator p.IAllocator, encryptor p.IEncryptor, decryptor p.IDecryptor) IProtocol {
proto := &protocol{
IMessageFactoryManager: newMessageFactoryManager(),
allocator: &p.NonAllocator{},
encryptor: &p.NonEncryptor{},
decryptor: &p.NonDecryptor{},
}
if allocator != nil {
proto.allocator = allocator
}
if encryptor != nil {
proto.encryptor = encryptor
}
if decryptor != nil {
proto.decryptor = decryptor
}
return proto
}
func (p *protocol) Encode(iMsg IMessage) ([]byte, error) {
id := []byte(iMsg.MessageID())
idSize := len(id)
data := p.allocator.Alloc(iMsg.Size() + 2 + idSize)
// 拷贝消息id
binary.BigEndian.PutUint16(data[:2], uint16(idSize))
copy(data[2:2+idSize], id)
// 拷贝消息
if _, err := iMsg.MarshalTo(data[2+idSize:]); err != nil {
return nil, fmt.Errorf("marshal [%v] fail, %v", iMsg, err)
}
err := p.encryptor.Encrypt(data)
if err != nil {
return nil, fmt.Errorf("encrypt [%v] fail, %v", iMsg, err)
}
return data, err
}
func (p *protocol) Decode(data []byte) (IMessage, error) {
err := p.decryptor.Decrypt(data)
if err != nil {
return nil, fmt.Errorf("decrypt message fail, %v", err)
}
idSize := binary.BigEndian.Uint16(data[:2])
id := string(data[2 : 2+idSize])
iMsg, err := p.Produce(id)
if err != nil {
return nil, fmt.Errorf("produce message fail, %v", err)
}
if err := iMsg.Unmarshal(data[2+idSize:]); err != nil {
return nil, fmt.Errorf("unmarshal [%v] fail, %v", iMsg, err)
}
return iMsg, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/nggs/micro.git
git@gitee.com:nggs/micro.git
nggs
micro
micro
bac99dff65eb

搜索帮助