MCPcopy
hub / github.com/lxc/incus / DownloadFileHash

Function DownloadFileHash

shared/util/net.go:22–99  ·  view source on GitHub ↗

DownloadFileHash downloads a file while validating its hash.

(ctx context.Context, httpClient *http.Client, useragent string, progress func(progress ioprogress.ProgressData), canceler *cancel.HTTPRequestCanceller, filename string, url string, fileHash string, hashFunc hash.Hash, target io.WriteSeeker)

Source from the content-addressed store, hash-verified

20
21// DownloadFileHash downloads a file while validating its hash.
22func DownloadFileHash(ctx context.Context, httpClient *http.Client, useragent string, progress func(progress ioprogress.ProgressData), canceler *cancel.HTTPRequestCanceller, filename string, url string, fileHash string, hashFunc hash.Hash, target io.WriteSeeker) (int64, error) {
23 // Always seek to the beginning
24 _, _ = target.Seek(0, io.SeekStart)
25
26 var req *http.Request
27 var err error
28
29 // Prepare the download request
30 if ctx != nil {
31 req, err = http.NewRequestWithContext(ctx, "GET", url, nil)
32 } else {
33 req, err = http.NewRequest("GET", url, nil)
34 }
35
36 if err != nil {
37 return -1, err
38 }
39
40 if useragent != "" {
41 req.Header.Set("User-Agent", useragent)
42 }
43
44 // Perform the request
45 r, doneCh, err := cancel.CancelableDownload(canceler, httpClient.Do, req)
46 if err != nil {
47 return -1, err
48 }
49
50 defer logger.WarnOnError(r.Body.Close, "Failed to close response body")
51 defer close(doneCh)
52
53 if r.StatusCode != http.StatusOK {
54 if r.StatusCode == http.StatusNotFound {
55 return -1, fmt.Errorf("Unable to fetch %s: %w", url, ErrNotFound)
56 }
57
58 return -1, fmt.Errorf("Unable to fetch %s: %s", url, r.Status)
59 }
60
61 // Handle the data
62 body := r.Body
63 if progress != nil {
64 body = &ioprogress.ProgressReader{
65 ReadCloser: r.Body,
66 Tracker: &ioprogress.ProgressTracker{
67 Length: r.ContentLength,
68 Handler: func(percent int64, speed int64) {
69 if filename != "" {
70 progress(ioprogress.ProgressData{Text: fmt.Sprintf("%s: %d%% (%s/s)", filename, percent, units.GetByteSizeString(speed, 2))})
71 } else {
72 progress(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, units.GetByteSizeString(speed, 2))})
73 }
74 },
75 },
76 }
77 }
78
79 var size int64

Callers 1

GetImageFileMethod · 0.92

Calls 7

CancelableDownloadFunction · 0.92
WarnOnErrorFunction · 0.92
GetByteSizeStringFunction · 0.92
SafeCopyFunction · 0.85
SeekMethod · 0.80
ErrorfMethod · 0.80
SetMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…