mirror of
https://github.com/nbd-wtf/go-nostr.git
synced 2025-08-31 00:02:20 +02:00
RelayConnect() ensures there will be a connection, and handle connection errors better.
This commit is contained in:
20
relay.go
20
relay.go
@@ -39,15 +39,16 @@ type Relay struct {
|
|||||||
Connection *Connection
|
Connection *Connection
|
||||||
subscriptions s.MapOf[string, *Subscription]
|
subscriptions s.MapOf[string, *Subscription]
|
||||||
|
|
||||||
Notices chan string
|
Notices chan string
|
||||||
|
ConnectionError chan error
|
||||||
|
|
||||||
statusChans s.MapOf[string, chan Status]
|
statusChans s.MapOf[string, chan Status]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(url string) *Relay {
|
func RelayConnect(url string) (*Relay, error) {
|
||||||
return &Relay{
|
r := &Relay{URL: NormalizeURL(url)}
|
||||||
URL: NormalizeURL(url),
|
err := r.Connect()
|
||||||
subscriptions: s.MapOf[string, *Subscription]{},
|
return r, err
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Connect() error {
|
func (r *Relay) Connect() error {
|
||||||
@@ -60,6 +61,9 @@ func (r *Relay) Connect() error {
|
|||||||
return fmt.Errorf("error opening websocket to '%s': %w", r.URL, err)
|
return fmt.Errorf("error opening websocket to '%s': %w", r.URL, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
r.Notices = make(chan string)
|
||||||
|
r.ConnectionError = make(chan error)
|
||||||
|
|
||||||
conn := NewConnection(socket)
|
conn := NewConnection(socket)
|
||||||
r.Connection = conn
|
r.Connection = conn
|
||||||
|
|
||||||
@@ -67,8 +71,10 @@ func (r *Relay) Connect() error {
|
|||||||
for {
|
for {
|
||||||
typ, message, err := conn.socket.ReadMessage()
|
typ, message, err := conn.socket.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
r.ConnectionError <- err
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
if typ == websocket.PingMessage {
|
if typ == websocket.PingMessage {
|
||||||
conn.WriteMessage(websocket.PongMessage, nil)
|
conn.WriteMessage(websocket.PongMessage, nil)
|
||||||
continue
|
continue
|
||||||
|
@@ -65,7 +65,11 @@ func (r *RelayPool) Add(url string, policy RelayPoolPolicy) error {
|
|||||||
policy = SimplePolicy{Read: true, Write: true}
|
policy = SimplePolicy{Read: true, Write: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
relay := NewRelay(url)
|
relay, err := RelayConnect(url)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
r.Policies.Store(relay.URL, policy)
|
r.Policies.Store(relay.URL, policy)
|
||||||
r.Relays.Store(relay.URL, relay)
|
r.Relays.Store(relay.URL, relay)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user