Skip to content

Commit d802967

Browse files
committed
net/http/httptest: guarantee ResponseRecorder.Result returns a non-nil body
The doc for ResponseRecorder.Result guarantees that the body of the returned http.Response will be non-nil, but this is only true if the caller's body is non-nil. With this change, if the caller's body is nil then the returned response's body will be an empty io.ReadCloser.
1 parent e161b1e commit d802967

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/net/http/httptest/recorder.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,8 @@ func (rw *ResponseRecorder) Result() *http.Response {
184184
res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
185185
if rw.Body != nil {
186186
res.Body = ioutil.NopCloser(bytes.NewReader(rw.Body.Bytes()))
187+
} else {
188+
res.Body = http.NoBody
187189
}
188190
res.ContentLength = parseContentLength(res.Header.Get("Content-Length"))
189191

src/net/http/httptest/recorder_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package httptest
77
import (
88
"fmt"
99
"io"
10+
"io/ioutil"
1011
"net/http"
1112
"testing"
1213
)
@@ -39,6 +40,19 @@ func TestRecorder(t *testing.T) {
3940
return nil
4041
}
4142
}
43+
hasResultContents := func(want string) checkFunc {
44+
return func(rec *ResponseRecorder) error {
45+
contentBytes, err := ioutil.ReadAll(rec.Result().Body)
46+
if err != nil {
47+
return err
48+
}
49+
contents := string(contentBytes)
50+
if contents != want {
51+
return fmt.Errorf("Result().Body = %s; want %s", contents, want)
52+
}
53+
return nil
54+
}
55+
}
4256
hasContents := func(want string) checkFunc {
4357
return func(rec *ResponseRecorder) error {
4458
if rec.Body.String() != want {
@@ -286,4 +300,17 @@ func TestRecorder(t *testing.T) {
286300
}
287301
})
288302
}
303+
304+
// Test that even when a ResponseRecorder's body is nil,
305+
// it will not return a response with nil body.
306+
// Issue 26642
307+
t.Run("setting ResponseRecord.Body to nil", func(t *testing.T) {
308+
rec := NewRecorder()
309+
rec.Body = nil
310+
check := hasResultContents("")
311+
if err := check(rec); err != nil {
312+
t.Error(err)
313+
}
314+
})
315+
289316
}

0 commit comments

Comments
 (0)