Skip to content

Commit

Permalink
Fix dial panic when ctx is nil
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
guseggert committed Jan 30, 2023
1 parent 14fb98e commit 7fd6136
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
5 changes: 4 additions & 1 deletion dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ func handshakeRequest(ctx context.Context, urls string, opts *DialOptions, copts
return nil, fmt.Errorf("unexpected url scheme: %q", u.Scheme)
}

req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return nil, fmt.Errorf("failed to build HTTP request: %w", err)
}
req.Header = opts.HTTPHeader.Clone()
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "websocket")
Expand Down
22 changes: 16 additions & 6 deletions dial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ func TestBadDials(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
url string
opts *DialOptions
rand readerFunc
name string
url string
opts *DialOptions
rand readerFunc
nilCtx bool
}{
{
name: "badURL",
Expand All @@ -46,15 +47,24 @@ func TestBadDials(t *testing.T) {
return 0, io.EOF
},
},
{
name: "nilContext",
url: "http://localhost",
nilCtx: true,
},
}

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

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
var ctx context.Context
var cancel func()
if !tc.nilCtx {
ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
}

if tc.rand == nil {
tc.rand = rand.Reader.Read
Expand Down

0 comments on commit 7fd6136

Please sign in to comment.