]> Cypherpunks repositories - gostls13.git/commitdiff
net/http/httptest: updated example to use Result()
authorDhaivat Pandit <dhaivatpandit@gmail.com>
Mon, 22 Aug 2016 17:29:02 +0000 (10:29 -0700)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 23 Aug 2016 05:12:10 +0000 (05:12 +0000)
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/27495
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>

src/net/http/httptest/example_test.go
src/net/http/httptest/recorder.go

index 124ce7513efc871ecfbf4120801c6b1daecd46ac..bd2c49642b6cc575dda21c212ab9319bdcbd107b 100644 (file)
@@ -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, "<html><body>Hello World!</body></html>")
        }
 
        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
+       // <html><body>Hello World!</body></html>
 }
 
 func ExampleServer() {
index 0ad26a3d418005c4f8ed92cba932c5fc9cbfef9e..725ba0b70a9dca8ea1e7a6b8c3ee7dab4aee83c4 100644 (file)
@@ -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 {