mirror of
https://github.com/nbd-wtf/go-nostr.git
synced 2025-08-09 04:31:47 +02:00
fix some concurrency things.
This commit is contained in:
23
relay.go
23
relay.go
@@ -97,13 +97,21 @@ func (r *Relay) Connect(ctx context.Context) error {
|
|||||||
r.Challenges = make(chan string)
|
r.Challenges = make(chan string)
|
||||||
r.Notices = make(chan string)
|
r.Notices = make(chan string)
|
||||||
|
|
||||||
|
// close these channels when the connection is dropped
|
||||||
|
go func() {
|
||||||
|
<-r.ConnectionContext.Done()
|
||||||
|
close(r.Challenges)
|
||||||
|
close(r.Notices)
|
||||||
|
}()
|
||||||
|
|
||||||
conn := NewConnection(socket)
|
conn := NewConnection(socket)
|
||||||
r.Connection = conn
|
r.Connection = conn
|
||||||
|
|
||||||
// ping every 29 seconds
|
// ping every 29 seconds
|
||||||
ticker := time.NewTicker(29 * time.Second)
|
|
||||||
defer ticker.Stop()
|
|
||||||
go func() {
|
go func() {
|
||||||
|
ticker := time.NewTicker(29 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
defer cancel()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
@@ -118,6 +126,7 @@ func (r *Relay) Connect(ctx context.Context) error {
|
|||||||
|
|
||||||
// handling received messages
|
// handling received messages
|
||||||
go func() {
|
go func() {
|
||||||
|
defer cancel()
|
||||||
for {
|
for {
|
||||||
typ, message, err := conn.socket.ReadMessage()
|
typ, message, err := conn.socket.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -152,13 +161,17 @@ func (r *Relay) Connect(ctx context.Context) error {
|
|||||||
var content string
|
var content string
|
||||||
json.Unmarshal(jsonMessage[1], &content)
|
json.Unmarshal(jsonMessage[1], &content)
|
||||||
go func() {
|
go func() {
|
||||||
r.Notices <- content
|
if r.ConnectionContext.Err() == nil {
|
||||||
|
r.Notices <- content
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
case "AUTH":
|
case "AUTH":
|
||||||
var challenge string
|
var challenge string
|
||||||
json.Unmarshal(jsonMessage[1], &challenge)
|
json.Unmarshal(jsonMessage[1], &challenge)
|
||||||
go func() {
|
go func() {
|
||||||
r.Challenges <- challenge
|
if r.ConnectionContext.Err() == nil {
|
||||||
|
r.Challenges <- challenge
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
case "EVENT":
|
case "EVENT":
|
||||||
if len(jsonMessage) < 3 {
|
if len(jsonMessage) < 3 {
|
||||||
@@ -235,8 +248,6 @@ func (r *Relay) Connect(ctx context.Context) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cancel()
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
Reference in New Issue
Block a user