Move I/O utilities to io.go

This commit is contained in:
Adnan Maolood
2021-02-23 20:49:42 -05:00
parent a65c3c3d4f
commit e8d98ef4ec
4 changed files with 105 additions and 103 deletions

View File

@@ -81,7 +81,7 @@ func ReadResponse(rc io.ReadCloser) (*Response, error) {
}
if resp.Status.Class() == StatusSuccess {
resp.body = newReadCloserBody(br, rc)
resp.body = newBufReadCloser(br, rc)
} else {
resp.body = nopReadCloser{}
rc.Close()
@@ -89,43 +89,6 @@ func ReadResponse(rc io.ReadCloser) (*Response, error) {
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
}
func newReadCloserBody(br *bufio.Reader, rc io.ReadCloser) io.ReadCloser {
body := &readCloserBody{ReadCloser: rc}
if br.Buffered() != 0 {
body.br = br
}
return body
}
func (b *readCloserBody) Read(p []byte) (n int, err error) {
if b.br != nil {
if n := b.br.Buffered(); len(p) > n {
p = p[:n]
}
n, err = b.br.Read(p)
if b.br.Buffered() == 0 {
b.br = nil
}
return n, err
}
return b.ReadCloser.Read(p)
}
// Read reads data from the response body.
// The response body is streamed on demand as Read is called.
func (r *Response) Read(p []byte) (n int, err error) {