Commit cd5ab979 authored by Dhaivat Pandit's avatar Dhaivat Pandit Committed by Brad Fitzpatrick

net/http/httptest: updated example to use Result()

example for httptest.Recorder was inspecting Recoder directly.
Using Result() to convert Recorder into a http.Response yields a much
better user experience.

Closes #16837

Change-Id: Id0e636c12cd6adb1ba11f89953ff2b0f43758cf3
Reviewed-on: https://go-review.googlesource.com/27495Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
parent 93b753f5
...@@ -6,6 +6,7 @@ package httptest_test ...@@ -6,6 +6,7 @@ package httptest_test
import ( import (
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
...@@ -14,15 +15,24 @@ import ( ...@@ -14,15 +15,24 @@ import (
func ExampleResponseRecorder() { func ExampleResponseRecorder() {
handler := func(w http.ResponseWriter, r *http.Request) { handler := func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "something failed", http.StatusInternalServerError) io.WriteString(w, "<html><body>Hello World!</body></html>")
} }
req := httptest.NewRequest("GET", "http://example.com/foo", nil) req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
handler(w, req) handler(w, req)
fmt.Printf("%d - %s", w.Code, w.Body.String()) resp := w.Result()
// Output: 500 - something failed 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
// <html><body>Hello World!</body></html>
} }
func ExampleServer() { func ExampleServer() {
......
...@@ -136,6 +136,9 @@ func (rw *ResponseRecorder) Flush() { ...@@ -136,6 +136,9 @@ func (rw *ResponseRecorder) Flush() {
// first write call, or at the time of this call, if the handler never // first write call, or at the time of this call, if the handler never
// did a write. // 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. // Result must only be called after the handler has finished running.
func (rw *ResponseRecorder) Result() *http.Response { func (rw *ResponseRecorder) Result() *http.Response {
if rw.result != nil { if rw.result != nil {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment