Skip to content

Commit 8cf69c9

Browse files
committed
fix: Prevent panic in Dial when response body is nil and add test for nil body handling
1 parent 71b3b5d commit 8cf69c9

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

dial.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ func dial(ctx context.Context, urls string, opts *DialOptions, rand io.Reader) (
160160
respBody := resp.Body
161161
resp.Body = nil
162162
defer func() {
163-
if err != nil {
163+
if err != nil && respBody != nil {
164164
// Capture a limited portion of the response body for easier debugging,
165165
// following the limit configured by MaxErrorResponseBodyBytes.
166166
limit := opts.MaxErrorResponseBodyBytes

dial_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,3 +515,35 @@ func TestDial_ErrorResponseBodyCapture_Disabled_NoBodyWithClose(t *testing.T) {
515515
t.Fatal("expected original body to be closed")
516516
}
517517
}
518+
519+
func TestDial_ErrorResponseBodyCapture_NilBody(t *testing.T) {
520+
t.Parallel()
521+
522+
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
523+
defer cancel()
524+
525+
rt := func(r *http.Request) (*http.Response, error) {
526+
// No body returned; ensure Dial does not panic when attempting capture.
527+
return &http.Response{
528+
StatusCode: http.StatusForbidden,
529+
Body: nil,
530+
}, nil
531+
}
532+
533+
_, resp, err := websocket.Dial(ctx, "ws://example.com", &websocket.DialOptions{
534+
HTTPClient: mockHTTPClient(rt),
535+
})
536+
assert.Error(t, err)
537+
if resp == nil {
538+
t.Fatal("expected non-nil resp")
539+
}
540+
assert.Equal(t, "StatusCode", http.StatusForbidden, resp.StatusCode)
541+
if resp.Body == nil {
542+
return
543+
}
544+
b, rerr := io.ReadAll(resp.Body)
545+
assert.Success(t, rerr)
546+
if len(b) != 0 {
547+
t.Fatalf("expected empty body when original body is nil, got %d bytes", len(b))
548+
}
549+
}

0 commit comments

Comments
 (0)