Guarantee that (*Response).Body is not nil
This commit is contained in:
parent
2b17f3d8eb
commit
31de8d49b0
3
doc.go
3
doc.go
@ -8,11 +8,8 @@ Client is a Gemini client.
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
if resp.Body != nil {
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
// ...
|
// ...
|
||||||
}
|
|
||||||
// ...
|
|
||||||
|
|
||||||
Server is a Gemini server.
|
Server is a Gemini server.
|
||||||
|
|
||||||
|
@ -145,10 +145,10 @@ func main() {
|
|||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
// Handle response
|
// Handle response
|
||||||
if resp.Status.Class() == gemini.StatusClassSuccess {
|
if resp.Status.Class() == gemini.StatusClassSuccess {
|
||||||
defer resp.Body.Close()
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
16
response.go
16
response.go
@ -18,7 +18,10 @@ type Response struct {
|
|||||||
// Meta should not be longer than 1024 bytes.
|
// Meta should not be longer than 1024 bytes.
|
||||||
Meta string
|
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
|
Body io.ReadCloser
|
||||||
|
|
||||||
// TLS contains information about the TLS connection on which the response
|
// 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 {
|
if resp.Status.Class() == StatusClassSuccess {
|
||||||
resp.Body = newReadCloserBody(br, rc)
|
resp.Body = newReadCloserBody(br, rc)
|
||||||
} else {
|
} else {
|
||||||
|
resp.Body = nopReadCloser{}
|
||||||
rc.Close()
|
rc.Close()
|
||||||
}
|
}
|
||||||
return resp, nil
|
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 {
|
type readCloserBody struct {
|
||||||
br *bufio.Reader // used until empty
|
br *bufio.Reader // used until empty
|
||||||
io.ReadCloser
|
io.ReadCloser
|
||||||
|
Loading…
Reference in New Issue
Block a user