Skip to content

Commit b2ad2ac

Browse files
authored
Merge pull request #74 from hyperledger/websocket-close
Close ws client if context is canceled
2 parents 1f12860 + 22922cd commit b2ad2ac

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

pkg/wsclient/wsclient.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ type WSPreConnectHandler func(ctx context.Context) error
115115
type WSPostConnectHandler func(ctx context.Context, w WSClient) error
116116

117117
func New(ctx context.Context, config *WSConfig, beforeConnect WSPreConnectHandler, afterConnect WSPostConnectHandler) (WSClient, error) {
118-
118+
l := log.L(ctx)
119119
wsURL, err := buildWSUrl(ctx, config)
120120
if err != nil {
121121
return nil, err
@@ -160,6 +160,16 @@ func New(ctx context.Context, config *WSConfig, beforeConnect WSPreConnectHandle
160160
w.headers.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", authUsername, authPassword)))))
161161
}
162162

163+
go func() {
164+
select {
165+
case <-ctx.Done():
166+
l.Tracef("WS %s closing due to canceled context", w.url)
167+
w.Close()
168+
case <-w.closing:
169+
l.Tracef("WS %s closing", w.url)
170+
}
171+
}()
172+
163173
return w, nil
164174
}
165175

pkg/wsclient/wsclient_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,3 +626,14 @@ func TestTestTLSServerFailsBadCerts(t *testing.T) {
626626
assert.Error(t, err)
627627

628628
}
629+
630+
func TestWSClientContextClosed(t *testing.T) {
631+
ctx, cancel := context.WithCancel(context.Background())
632+
cancel()
633+
wsConfig := generateConfig()
634+
wsc, err := New(ctx, wsConfig, nil, nil)
635+
assert.NoError(t, err)
636+
assert.NotNil(t, wsc)
637+
err = wsc.Send(context.Background(), []byte{})
638+
assert.Regexp(t, "FF00147", err)
639+
}

0 commit comments

Comments
 (0)