From aca6f2f3ad81ba77ee0c06323f52f454ab6a8d98 Mon Sep 17 00:00:00 2001 From: alexvanin Date: Mon, 18 May 2020 16:23:51 +0300 Subject: [PATCH] rpc/client: handle client creation error in new wsclient Client returns error if it can't parse endpoint string. WSClient should check client error or there could be panic at `cl.cli = nil` expression. --- pkg/rpc/client/wsclient.go | 4 ++++ pkg/rpc/client/wsclient_test.go | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/pkg/rpc/client/wsclient.go b/pkg/rpc/client/wsclient.go index 24363f1dd..3f469a86a 100644 --- a/pkg/rpc/client/wsclient.go +++ b/pkg/rpc/client/wsclient.go @@ -71,6 +71,10 @@ const ( // connection). You need to use websocket URL for it like `ws://1.2.3.4/ws`. func NewWS(ctx context.Context, endpoint string, opts Options) (*WSClient, error) { cl, err := New(ctx, endpoint, opts) + if err != nil { + return nil, err + } + cl.cli = nil dialer := websocket.Dialer{HandshakeTimeout: opts.DialTimeout} diff --git a/pkg/rpc/client/wsclient_test.go b/pkg/rpc/client/wsclient_test.go index 55224cf35..a31a6beb0 100644 --- a/pkg/rpc/client/wsclient_test.go +++ b/pkg/rpc/client/wsclient_test.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -297,3 +298,17 @@ func TestWSFilteredSubscriptions(t *testing.T) { }) } } + +func TestNewWS(t *testing.T) { + srv := initTestServer(t, "") + defer srv.Close() + + t.Run("good", func(t *testing.T) { + _, err := NewWS(context.TODO(), httpURLtoWS(srv.URL), Options{}) + require.NoError(t, err) + }) + t.Run("bad URL", func(t *testing.T) { + _, err := NewWS(context.TODO(), strings.Trim(srv.URL, "http://"), Options{}) + require.Error(t, err) + }) +}