From 9b89a49e5e29c6937094650f0fd3f99bd1f830c2 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Fri, 21 Apr 2023 07:45:23 -0300 Subject: [PATCH] cancel relay context when calling `.Close()`. fixing https://github.com/nbd-wtf/go-nostr/issues/76#issuecomment-1517251898 --- relay.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/relay.go b/relay.go index 328aa39..dacfd8b 100644 --- a/relay.go +++ b/relay.go @@ -42,10 +42,11 @@ type Relay struct { Connection *Connection subscriptions s.MapOf[string, *Subscription] - Challenges chan string // NIP-42 Challenges - Notices chan string - ConnectionError error - ConnectionContext context.Context // will be canceled when the connection closes + Challenges chan string // NIP-42 Challenges + Notices chan string + ConnectionError error + ConnectionContext context.Context // will be canceled when the connection closes + connectionContextCancel context.CancelFunc okCallbacks s.MapOf[string, func(bool, string)] mutex sync.RWMutex @@ -75,6 +76,7 @@ func (r *Relay) String() string { func (r *Relay) Connect(ctx context.Context) error { connectionContext, cancel := context.WithCancel(ctx) r.ConnectionContext = connectionContext + r.connectionContextCancel = cancel if r.URL == "" { cancel() @@ -470,5 +472,11 @@ func (r *Relay) PrepareSubscription(ctx context.Context) *Subscription { } func (r *Relay) Close() error { + if r.connectionContextCancel == nil { + return fmt.Errorf("relay not connected") + } + + r.connectionContextCancel() + r.connectionContextCancel = nil return r.Connection.Close() }