Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7fd6136

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 functionpanics because it assumes the req is never nil. This checks thereturning error and returns it, so that callers get an error insteadof a panic in that scenario.
1 parent14fb98e commit7fd6136

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

‎dial.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,10 @@ func handshakeRequest(ctx context.Context, urls string, opts *DialOptions, copts
157157
returnnil,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+
iferr!=nil {
162+
returnnil,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‎

Lines changed: 16 additions & 6 deletions
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-
namestring
27-
urlstring
28-
opts*DialOptions
29-
randreaderFunc
26+
namestring
27+
urlstring
28+
opts*DialOptions
29+
randreaderFunc
30+
nilCtxbool
3031
}{
3132
{
3233
name:"badURL",
@@ -46,15 +47,24 @@ func TestBadDials(t *testing.T) {
4647
return0,io.EOF
4748
},
4849
},
50+
{
51+
name:"nilContext",
52+
url:"http://localhost",
53+
nilCtx:true,
54+
},
4955
}
5056

5157
for_,tc:=rangetestCases {
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-
defercancel()
62+
varctx context.Context
63+
varcancelfunc()
64+
if!tc.nilCtx {
65+
ctx,cancel=context.WithTimeout(context.Background(),time.Second*5)
66+
defercancel()
67+
}
5868

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp