libs5-go/net/net.go

68 lines
1.3 KiB
Go
Raw Normal View History

2024-01-06 11:33:46 +00:00
package net
import (
"errors"
"net/url"
"sync"
)
var (
ErrTransportNotSupported = errors.New("no static method registered for type")
)
2024-01-06 11:33:46 +00:00
type TransportPeerConfig struct {
Socket interface{}
Uris []*url.URL
}
type PeerStatic interface {
Connect(uri *url.URL) (interface{}, error) // Returns a connection/socket
}
type PeerFactory interface {
NewPeer(options *TransportPeerConfig) (Peer, error)
}
var (
transports sync.Map
)
func init() {
transports = sync.Map{}
2024-01-07 11:49:27 +00:00
RegisterTransport("ws", &WebSocketPeer{})
RegisterTransport("wss", &WebSocketPeer{})
2024-01-06 11:33:46 +00:00
}
func RegisterTransport(peerType string, factory interface{}) {
if _, ok := factory.(PeerFactory); !ok {
panic("factory must implement PeerFactory")
}
if _, ok := factory.(PeerStatic); !ok {
panic("factory must implement PeerStatic")
}
transports.Store(peerType, factory)
}
func CreateTransportSocket(peerType string, uri *url.URL) (interface{}, error) {
static, ok := transports.Load(peerType)
if !ok {
return nil, ErrTransportNotSupported
2024-01-06 11:33:46 +00:00
}
t, err := static.(PeerStatic).Connect(uri)
2024-01-07 11:51:40 +00:00
return t, err
2024-01-06 11:33:46 +00:00
}
func CreateTransportPeer(peerType string, options *TransportPeerConfig) (Peer, error) {
2024-01-06 11:33:46 +00:00
factory, ok := transports.Load(peerType)
if !ok {
return nil, errors.New("no factory registered for type: " + peerType)
}
t, err := factory.(PeerFactory).NewPeer(options)
return t, err
2024-01-06 11:33:46 +00:00
}