From 6fa0c539bd952fee3dfe303ebfdad6bca60126a1 Mon Sep 17 00:00:00 2001 From: DarthSim Date: Mon, 21 Jan 2019 15:04:54 +0600 Subject: [PATCH] Grow download buffer to Content-Length value --- download.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/download.go b/download.go index d8371247..a273a11c 100644 --- a/download.go +++ b/download.go @@ -103,10 +103,17 @@ func readAndCheckImage(ctx context.Context, res *http.Response) (context.Context return ctx, cancel, err } - if cls := res.Header.Get("Content-Length"); len(cls) > 0 { - if cl, err := strconv.Atoi(cls); err == nil && cl > buf.Len() && cl > buf.Cap() { - buf.Grow(cl - buf.Len()) - } + var contentLength int + + if res.ContentLength > 0 { + contentLength = int(res.ContentLength) + } else { + // ContentLength wasn't set properly, trying to parse the header + contentLength, _ = strconv.Atoi(res.Header.Get("Content-Length")) + } + + if contentLength > buf.Cap() { + buf.Grow(contentLength - buf.Len()) } if _, err = buf.ReadFrom(res.Body); err != nil {