Skip to content

Commit 7fd6136

Browse files
committed
Fix dial panic when ctx is nil
When the ctx is nil, http.NewRequestWithContext returns a "net/http: nil Context" error and a nil request. In this case, the dial function panics because it assumes the req is never nil. This checks the returning error and returns it, so that callers get an error instead of a panic in that scenario.
1 parent 14fb98e commit 7fd6136

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

dial.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,10 @@ func handshakeRequest(ctx context.Context, urls string, opts *DialOptions, copts
157157
return nil, fmt.Errorf("unexpected url scheme: %q", u.Scheme)
158158
}
159159

160-
req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
160+
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
161+
if err != nil {
162+
return nil, fmt.Errorf("failed to build HTTP request: %w", err)
163+
}
161164
req.Header = opts.HTTPHeader.Clone()
162165
req.Header.Set("Connection", "Upgrade")
163166
req.Header.Set("Upgrade", "websocket")

dial_test.go

+16-6
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,11 @@ func TestBadDials(t *testing.T) {
2323
t.Parallel()
2424

2525
testCases := []struct {
26-
name string
27-
url string
28-
opts *DialOptions
29-
rand readerFunc
26+
name string
27+
url string
28+
opts *DialOptions
29+
rand readerFunc
30+
nilCtx bool
3031
}{
3132
{
3233
name: "badURL",
@@ -46,15 +47,24 @@ func TestBadDials(t *testing.T) {
4647
return 0, io.EOF
4748
},
4849
},
50+
{
51+
name: "nilContext",
52+
url: "http://localhost",
53+
nilCtx: true,
54+
},
4955
}
5056

5157
for _, tc := range testCases {
5258
tc := tc
5359
t.Run(tc.name, func(t *testing.T) {
5460
t.Parallel()
5561

56-
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
57-
defer cancel()
62+
var ctx context.Context
63+
var cancel func()
64+
if !tc.nilCtx {
65+
ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
66+
defer cancel()
67+
}
5868

5969
if tc.rand == nil {
6070
tc.rand = rand.Reader.Read

0 commit comments

Comments
 (0)