diff --git a/src/net/http/httptest/example_test.go b/src/net/http/httptest/example_test.go index 124ce7513ef..bd2c49642b6 100644 --- a/src/net/http/httptest/example_test.go +++ b/src/net/http/httptest/example_test.go @@ -6,6 +6,7 @@ package httptest_test import ( "fmt" + "io" "io/ioutil" "log" "net/http" @@ -14,15 +15,24 @@ import ( func ExampleResponseRecorder() { handler := func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "something failed", http.StatusInternalServerError) + io.WriteString(w, "Hello World!") } req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() handler(w, req) - fmt.Printf("%d - %s", w.Code, w.Body.String()) - // Output: 500 - something failed + resp := w.Result() + body, _ := ioutil.ReadAll(resp.Body) + + fmt.Println(resp.StatusCode) + fmt.Println(resp.Header.Get("Content-Type")) + fmt.Println(string(body)) + + // Output: + // 200 + // text/html; charset=utf-8 + // Hello World! } func ExampleServer() { diff --git a/src/net/http/httptest/recorder.go b/src/net/http/httptest/recorder.go index 0ad26a3d418..725ba0b70a9 100644 --- a/src/net/http/httptest/recorder.go +++ b/src/net/http/httptest/recorder.go @@ -136,6 +136,9 @@ func (rw *ResponseRecorder) Flush() { // first write call, or at the time of this call, if the handler never // did a write. // +// The Response.Body is guaranteed to be non-nil and Body.Read call is +// guaranteed to not return any error other than io.EOF. +// // Result must only be called after the handler has finished running. func (rw *ResponseRecorder) Result() *http.Response { if rw.result != nil {