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.
92 lines
2.4 KiB
Go
92 lines
2.4 KiB
Go
package version
|
|
|
|
import (
|
|
"context"
|
|
|
|
protocolpkg "github.com/noahlann/nnet/pkg/protocol"
|
|
)
|
|
|
|
// HeaderIdentifier 基于帧头的版本识别器
|
|
type HeaderIdentifier struct {
|
|
field string
|
|
offset int
|
|
mapping map[interface{}]string
|
|
}
|
|
|
|
// NewHeaderIdentifier 创建基于帧头的版本识别器
|
|
func NewHeaderIdentifier(field string, offset int, mapping map[interface{}]string) protocolpkg.VersionIdentifier {
|
|
return &HeaderIdentifier{
|
|
field: field,
|
|
offset: offset,
|
|
mapping: mapping,
|
|
}
|
|
}
|
|
|
|
// Identify 识别协议版本
|
|
func (i *HeaderIdentifier) Identify(data []byte, ctx context.Context) (string, error) {
|
|
if len(data) < i.offset+1 {
|
|
return "", protocolpkg.NewError("data too short")
|
|
}
|
|
|
|
// 从指定偏移量读取版本信息
|
|
versionByte := data[i.offset]
|
|
|
|
// 查找映射
|
|
if version, ok := i.mapping[versionByte]; ok {
|
|
return version, nil
|
|
}
|
|
|
|
return "", protocolpkg.NewError("version not found")
|
|
}
|
|
|
|
// MessageHeaderIdentifier 基于消息头的版本识别器
|
|
type MessageHeaderIdentifier struct {
|
|
path string
|
|
mapping map[interface{}]string
|
|
}
|
|
|
|
// NewMessageHeaderIdentifier 创建基于消息头的版本识别器
|
|
func NewMessageHeaderIdentifier(path string, mapping map[interface{}]string) protocolpkg.VersionIdentifier {
|
|
return &MessageHeaderIdentifier{
|
|
path: path,
|
|
mapping: mapping,
|
|
}
|
|
}
|
|
|
|
// Identify 识别协议版本
|
|
func (i *MessageHeaderIdentifier) Identify(data []byte, ctx context.Context) (string, error) {
|
|
// 这里需要解析消息头,实际实现可能需要根据具体的消息格式来解析
|
|
// 简化实现:假设消息头包含版本信息
|
|
if len(data) < 1 {
|
|
return "", protocolpkg.NewError("data too short")
|
|
}
|
|
|
|
versionByte := data[0]
|
|
if version, ok := i.mapping[versionByte]; ok {
|
|
return version, nil
|
|
}
|
|
|
|
return "", protocolpkg.NewError("version not found")
|
|
}
|
|
|
|
// CustomIdentifier 自定义版本识别器
|
|
type CustomIdentifier struct {
|
|
fn func(data []byte, ctx context.Context) (string, error)
|
|
}
|
|
|
|
// NewCustomIdentifier 创建自定义版本识别器
|
|
func NewCustomIdentifier(fn func(data []byte, ctx context.Context) (string, error)) protocolpkg.VersionIdentifier {
|
|
return &CustomIdentifier{
|
|
fn: fn,
|
|
}
|
|
}
|
|
|
|
// Identify 识别协议版本
|
|
func (i *CustomIdentifier) Identify(data []byte, ctx context.Context) (string, error) {
|
|
if i.fn == nil {
|
|
return "", protocolpkg.NewError("identifier function is nil")
|
|
}
|
|
return i.fn(data, ctx)
|
|
}
|
|
|