From 38cfab5bd46c8765fc64a39b3cecefea6dd388c0 Mon Sep 17 00:00:00 2001 From: James Pond Date: Mon, 15 Jan 2024 12:29:29 -0300 Subject: [PATCH] Preallocate buffer if possible Signed-off-by: James Pond --- client.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/client.go b/client.go index bd79b60..421671e 100644 --- a/client.go +++ b/client.go @@ -219,9 +219,15 @@ func (c *Client) do(ctx context.Context, req *http.Request) (*Response, error) { return nil, fmt.Errorf("%w: %d", ErrRequestFailed, resp.StatusCode) } - var buffer bytes.Buffer + var buffer *bytes.Buffer - _, err = io.Copy(&buffer, resp.Body) + if resp.ContentLength > 0 { + buffer = bytes.NewBuffer(make([]byte, 0, resp.ContentLength)) + } else { + buffer = bytes.NewBuffer(make([]byte, 0)) + } + + _, err = io.Copy(buffer, resp.Body) if err != nil { return nil, fmt.Errorf("%w", err) }