safeFileFromURL downloads the file from the specified url (using safeHTTPClient) and creates a new filesystem.File value from its content (limited to DefaultMaxBodySize). @todo Evaluate with the refactoring if worth exporting/replacing filesystem.NewFileFromURL (or redefine as NewUnsafeFileFromURL)
(ctx context.Context, url string)
| 482 | // |
| 483 | // @todo Evaluate with the refactoring if worth exporting/replacing filesystem.NewFileFromURL (or redefine as NewUnsafeFileFromURL). |
| 484 | func safeFileFromURL(ctx context.Context, url string) (*filesystem.File, error) { |
| 485 | req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 486 | if err != nil { |
| 487 | return nil, err |
| 488 | } |
| 489 | |
| 490 | client := safeHTTPClient() |
| 491 | |
| 492 | res, err := client.Do(req) |
| 493 | if err != nil { |
| 494 | return nil, err |
| 495 | } |
| 496 | defer res.Body.Close() |
| 497 | |
| 498 | if res.StatusCode < 200 || res.StatusCode > 399 { |
| 499 | return nil, fmt.Errorf("failed to download url %s (%d)", url, res.StatusCode) |
| 500 | } |
| 501 | |
| 502 | body := io.LimitReader(res.Body, DefaultMaxBodySize) |
| 503 | |
| 504 | var buf bytes.Buffer |
| 505 | if _, err = io.Copy(&buf, body); err != nil { |
| 506 | return nil, err |
| 507 | } |
| 508 | |
| 509 | return filesystem.NewFileFromBytes(buf.Bytes(), path.Base(url)) |
| 510 | } |
no test coverage detected
searching dependent graphs…