diff options
| -rw-r--r-- | doc.go | 5 | ||||
| -rw-r--r-- | examples/client.go | 2 | ||||
| -rw-r--r-- | response.go | 16 |
3 files changed, 17 insertions, 6 deletions
@@ -8,10 +8,7 @@ Client is a Gemini client. if err != nil { // handle error } - if resp.Body != nil { - defer resp.Body.Close() - // ... - } + defer resp.Body.Close() // ... Server is a Gemini server. diff --git a/examples/client.go b/examples/client.go index 97a197a..4135070 100644 --- a/examples/client.go +++ b/examples/client.go @@ -145,10 +145,10 @@ func main() { fmt.Println(err) os.Exit(1) } + defer resp.Body.Close() // Handle response if resp.Status.Class() == gemini.StatusClassSuccess { - defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) diff --git a/response.go b/response.go index 2d7cd7b..b8f9649 100644 --- a/response.go +++ b/response.go @@ -18,7 +18,10 @@ type Response struct { // Meta should not be longer than 1024 bytes. Meta string - // Body contains the response body for successful responses. + // Body represents the response body. + // Body is guaranteed to always be non-nil. + // + // The response body is streamed on demand as the Body field is read. Body io.ReadCloser // TLS contains information about the TLS connection on which the response @@ -83,11 +86,22 @@ func ReadResponse(rc io.ReadCloser) (*Response, error) { if resp.Status.Class() == StatusClassSuccess { resp.Body = newReadCloserBody(br, rc) } else { + resp.Body = nopReadCloser{} rc.Close() } return resp, nil } +type nopReadCloser struct{} + +func (nopReadCloser) Read(p []byte) (int, error) { + return 0, io.EOF +} + +func (nopReadCloser) Close() error { + return nil +} + type readCloserBody struct { br *bufio.Reader // used until empty io.ReadCloser |