You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.2 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package protocol
import (
"encoding/json"
"sync"
protocolpkg "github.com/noahlann/nnet/pkg/protocol"
)
// frameHeader 协议帧头实现
type frameHeader struct {
data map[string]interface{}
mu sync.RWMutex
}
// NewFrameHeader 创建新的协议帧头
func NewFrameHeader() protocolpkg.FrameHeader {
return &frameHeader{
data: make(map[string]interface{}),
}
}
// Get 获取帧头字段
func (h *frameHeader) Get(key string) interface{} {
h.mu.RLock()
defer h.mu.RUnlock()
return h.data[key]
}
// Set 设置帧头字段
func (h *frameHeader) Set(key string, value interface{}) {
h.mu.Lock()
defer h.mu.Unlock()
if h.data == nil {
h.data = make(map[string]interface{})
}
h.data[key] = value
}
// Encode 编码为字节使用JSON格式
// 注意:这是通用编码,用于调试和通用场景
// 具体的协议实现应该使用Protocol.Encode方法来编码完整的消息包括帧头和数据
func (h *frameHeader) Encode() ([]byte, error) {
h.mu.RLock()
defer h.mu.RUnlock()
// 如果数据为空返回空JSON对象
if len(h.data) == 0 {
return []byte("{}"), nil
}
// 使用JSON编码
return json.Marshal(h.data)
}
// Decode 从字节解码使用JSON格式
// 注意:这是通用解码,用于调试和通用场景
// 具体的协议实现应该使用Protocol.Decode方法来解码完整的消息包括帧头和数据
func (h *frameHeader) Decode(data []byte) error {
if len(data) == 0 {
return nil
}
h.mu.Lock()
defer h.mu.Unlock()
// 如果data为空初始化为空map
if h.data == nil {
h.data = make(map[string]interface{})
}
// 使用JSON解码
var decodedData map[string]interface{}
if err := json.Unmarshal(data, &decodedData); err != nil {
return err
}
// 合并解码后的数据(保留原有数据,新数据覆盖旧数据)
for k, v := range decodedData {
h.data[k] = v
}
return nil
}
// Clone 克隆帧头(深拷贝)
func (h *frameHeader) Clone() protocolpkg.FrameHeader {
h.mu.RLock()
defer h.mu.RUnlock()
cloned := &frameHeader{
data: make(map[string]interface{}),
}
// 深拷贝所有字段
for k, v := range h.data {
cloned.data[k] = v
}
return cloned
}