From 33c1dc435de5247d65ed4bdbf76d4e884280379f Mon Sep 17 00:00:00 2001 From: Adnan Maolood Date: Sat, 31 Oct 2020 23:04:47 -0400 Subject: [PATCH] Guarantee that (*Response).Body is non-nil --- examples/client.go | 7 ++++--- response.go | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/examples/client.go b/examples/client.go index 4c9b172..ec8b221 100644 --- a/examples/client.go +++ b/examples/client.go @@ -76,17 +76,18 @@ func main() { resp, err := client.Do(req) if err != nil { - log.Fatal(err) + fmt.Println(err) + os.Exit(1) } + defer resp.Body.Close() if resp.Status.Class() == gemini.StatusClassSuccess { - defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Print(string(body)) } else { - log.Fatalf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta) + fmt.Printf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta) } } diff --git a/response.go b/response.go index 8f24419..89d4d5c 100644 --- a/response.go +++ b/response.go @@ -2,8 +2,10 @@ package gemini import ( "bufio" + "bytes" "crypto/tls" "io" + "io/ioutil" "strconv" ) @@ -19,6 +21,7 @@ type Response struct { Meta string // Body contains the response body for successful responses. + // Body is guaranteed to be non-nil. Body io.ReadCloser // Request is the request that was sent to obtain this response. @@ -83,6 +86,8 @@ func (resp *Response) read(rc io.ReadCloser) error { if resp.Status.Class() == StatusClassSuccess { resp.Body = newReadCloserBody(br, rc) + } else { + resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) } return nil }