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.
This commit is contained in:
alexvanin 2020-05-18 16:23:51 +03:00
parent f0abbfd399
commit 8db714785d
2 changed files with 19 additions and 0 deletions

View file

@ -71,6 +71,10 @@ const (
// connection). You need to use websocket URL for it like `ws://1.2.3.4/ws`. // 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) { func NewWS(ctx context.Context, endpoint string, opts Options) (*WSClient, error) {
cl, err := New(ctx, endpoint, opts) cl, err := New(ctx, endpoint, opts)
if err != nil {
return nil, err
}
cl.cli = nil cl.cli = nil
dialer := websocket.Dialer{HandshakeTimeout: opts.DialTimeout} dialer := websocket.Dialer{HandshakeTimeout: opts.DialTimeout}

View file

@ -4,6 +4,7 @@ import (
"context" "context"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"time" "time"
@ -247,3 +248,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)
})
}