summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEmmanuel T Odeke <emmanuel@orijtech.com>2021-03-07 14:56:52 -0800
committerDamien Neil <dneil@google.com>2021-03-19 16:12:45 +0000
commite58fb90c753ce8ac1ccd6e26035e7ec0f4f108bc (patch)
treeff5f3a725233d67bdf0e2f1474740a4dcc1f8cd6
parenta937729c2c2f6950a32bc5cd0f5b88700882f078 (diff)
downloadgo-git-e58fb90c753ce8ac1ccd6e26035e7ec0f4f108bc.tar.gz
net/http: make ExampleGet show StatusCode checks for non-1XX,2XX responses
Updates ExampleGet to show how to handle bad responses with non-1XX,2XX status codes. Given that the canonical examples are copied, we need to have them properly check against failures. This is a bug I've seen often in the wild, that's exacerbated when for example unmarshalling JSON or even protobufs, and no errors are returned by the decoders, so code fails silently after making a request for example to a gateway that they were unauthorized to access. Fixes #39778 Change-Id: I1cd688f2fab47581c8cf228235d3662b4c8e4315 Reviewed-on: https://go-review.googlesource.com/c/go/+/299609 Trust: Emmanuel Odeke <emmanuel@orijtech.com> Run-TryBot: Emmanuel Odeke <emmanuel@orijtech.com> TryBot-Result: Go Bot <gobot@golang.org> Reviewed-by: Damien Neil <dneil@google.com>
-rw-r--r--src/net/http/example_test.go7
1 files changed, 5 insertions, 2 deletions
diff --git a/src/net/http/example_test.go b/src/net/http/example_test.go
index c677d52238..2f411d1d2e 100644
--- a/src/net/http/example_test.go
+++ b/src/net/http/example_test.go
@@ -45,12 +45,15 @@ func ExampleGet() {
if err != nil {
log.Fatal(err)
}
- robots, err := io.ReadAll(res.Body)
+ body, err := io.ReadAll(res.Body)
res.Body.Close()
+ if res.StatusCode > 299 {
+ log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
+ }
if err != nil {
log.Fatal(err)
}
- fmt.Printf("%s", robots)
+ fmt.Printf("%s", body)
}
func ExampleFileServer() {