Skip to content

Commit

Permalink
downloader: extract method (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmetc authored Aug 23, 2024
1 parent 44910ee commit d5404ed
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions downloader/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -519,18 +519,8 @@ func (d *Downloader) Download(ctx context.Context, url string) (bool, error) {
return false, BadHTTPCodeError{url, resp.StatusCode}
}

if d.maxSize > 0 {
contentLengthStr := resp.Header.Get("Content-Length")
if contentLengthStr != "" {
contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
if err != nil {
d.logger.Warnf("Failed to parse Content-Length header: %s", err)
} else if contentLength > d.maxSize {
return false, fmt.Errorf(
"refusing to download file larger than %d bytes: Content-Length=%d",
d.maxSize, contentLength)
}
}
if d.enforceMaxSize(resp) != nil {
return false, err
}

reader := resp.Body
Expand Down Expand Up @@ -659,3 +649,26 @@ func (d *Downloader) Download(ctx context.Context, url string) (bool, error) {

return true, nil
}

func (d *Downloader) enforceMaxSize(resp *http.Response) error {
if d.maxSize == 0 {
return nil
}

contentLengthStr := resp.Header.Get("Content-Length")
if contentLengthStr == "" {
return nil
}

contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
if err != nil {
d.logger.Warnf("failed to parse Content-Length header: %s", err)
}

if d.maxSize > 0 && contentLength > d.maxSize {
return fmt.Errorf("refusing to download file larger than %d bytes: Content-Length=%d",
d.maxSize, contentLength)
}

return nil
}

0 comments on commit d5404ed

Please sign in to comment.