Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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.
  • Loading branch information
guseggert committed Jan 30, 2023
commit 7fd613642282944805ba6f4f30bd5501b1f74e99
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