libs5-go/protocol/message.go

54 lines
1.2 KiB
Go
Raw Normal View History

2024-01-06 11:33:46 +00:00
package protocol
import (
"git.lumeweb.com/LumeWeb/libs5-go/protocol/base"
"git.lumeweb.com/LumeWeb/libs5-go/protocol/signed"
2024-01-06 11:33:46 +00:00
"git.lumeweb.com/LumeWeb/libs5-go/types"
"sync"
)
var (
messageTypes sync.Map
)
var (
_ base.IncomingMessage = (*base.IncomingMessageImpl)(nil)
2024-01-06 11:33:46 +00:00
)
func init() {
messageTypes = sync.Map{}
// Register factory functions instead of instances
RegisterMessageType(types.ProtocolMethodHandshakeOpen, func() base.IncomingMessage {
2024-01-06 11:33:46 +00:00
return NewHandshakeOpen([]byte{}, "")
})
2024-01-08 17:42:02 +00:00
RegisterMessageType(types.ProtocolMethodHashQuery, func() base.IncomingMessage {
return NewHashQuery()
})
RegisterMessageType(types.ProtocolMethodSignedMessage, func() base.IncomingMessage {
return signed.NewSignedMessage()
2024-01-06 11:33:46 +00:00
})
2024-01-08 17:42:02 +00:00
2024-01-06 11:33:46 +00:00
}
func RegisterMessageType(messageType types.ProtocolMethod, factoryFunc func() base.IncomingMessage) {
2024-01-06 11:33:46 +00:00
if factoryFunc == nil {
panic("factoryFunc cannot be nil")
}
messageTypes.Store(messageType, factoryFunc)
}
func GetMessageType(kind types.ProtocolMethod) (base.IncomingMessage, bool) {
2024-01-06 11:33:46 +00:00
value, ok := messageTypes.Load(kind)
if !ok {
return nil, false
}
factoryFunc, ok := value.(func() base.IncomingMessage)
2024-01-06 11:33:46 +00:00
if !ok {
return nil, false
}
return factoryFunc(), true
}