Documentation
¶
Overview ¶
Package download fetches files over HTTP with resume, retry, integrity checks and bounded concurrency, on the shared httpclient transport.
Download writes to Dest+".part" and renames on success, so Dest never holds a partial file. A partial file from an earlier attempt or run is continued with a Range request guarded by If-Range; the ETag (else Last-Modified) it was started with is stored in Dest+".part.meta". A 200 answer (range ignored or file changed) restarts from zero and a 416 answer discards the partial and restarts once. A partial without a stored validator is never resumed.
The length is checked against Content-Length or Content-Range (ErrBadLength, retryable after the partial is cleared), an optional digest is verified over the whole file including a resumed prefix (ErrChecksumMismatch, not retryable), and an optional size cap bounds the file. Progress is a plain callback; the package renders nothing.
Retry classification is the single httpclient.IsRetryable: *StatusError (408, 429, 5xx retried, other 4xx not), transport failures and ErrBadLength are retried, context errors never. Retry budget and backoff are Options.Retry, never package state. DownloadAll runs many Requests with bounded concurrency and returns one Result each.
Example ¶
package main
import (
"context"
"crypto/sha256"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/download"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "package payload")
}))
defer srv.Close()
dir, _ := os.MkdirTemp("", "download-example")
defer os.RemoveAll(dir)
dest := filepath.Join(dir, "pkg.bin")
sum := sha256.Sum256([]byte("package payload"))
err := download.Download(context.Background(), download.Request{
URL: srv.URL,
Dest: dest,
Checksum: &download.Checksum{New: sha256.New, Sum: sum[:]},
Progress: func(done, total int64) {
if done == total {
fmt.Println("complete:", done)
}
},
}, download.Options{})
data, _ := os.ReadFile(dest)
fmt.Println(string(data), err)
}
Output: complete: 15 package payload <nil>
Index ¶
Examples ¶
Constants ¶
const DefaultConcurrency = 4
DefaultConcurrency is the number of simultaneous transfers DownloadAll runs when Options.Concurrency is not positive.
Variables ¶
var ( // ErrBadLength is httpclient.ErrBadLength: the transfer ended with a length // other than the announced one. The partial file is discarded before the // error is reported, and it is retryable. ErrBadLength = httpclient.ErrBadLength // ErrTooLarge is httpclient.ErrTooLarge: the file exceeds Request.MaxBytes. ErrTooLarge = httpclient.ErrTooLarge // ErrChecksumMismatch is returned when the downloaded bytes do not match // Request.Checksum. The file is deleted and the error is not retryable. ErrChecksumMismatch = errors.New("download: checksum mismatch") )
Sentinel errors. Test with errors.Is.
Functions ¶
func Download ¶
Download fetches req.URL into req.Dest. A partial file left by an earlier attempt or run is continued with a Range request guarded by If-Range (the ETag, else Last-Modified, saved beside it), so a file that changed on the server is fetched afresh instead of spliced. Transient failures are retried with the client's backoff; each retry resumes from the bytes already on disk.
Cancelling ctx stops the transfer and keeps the partial file for the next run. The returned error wraps the last failure, so errors.As reaches *StatusError and errors.Is reaches the sentinels of this package.
Types ¶
type Checksum ¶
type Checksum struct {
// New constructs the hash, for example sha256.New.
New func() hash.Hash
// Sum is the expected digest.
Sum []byte
}
Checksum is an expected digest of the finished file.
func ParseChecksum ¶
ParseChecksum builds a Checksum from an algorithm name (sha256, sha512, sha1 or md5, case-insensitive) and a hex digest, as repository indexes publish them.
type Options ¶
type Options struct {
// Client carries the transfers (one transport, one retry classifier). Nil
// builds a client without an overall timeout, so a large file on a slow
// link is bounded by the context only.
Client *httpclient.Client
// Retry overrides the client's retry policy when it is not the zero value.
// With a nil Client and a zero Retry the defaults apply.
Retry httpclient.RetryPolicy
// Concurrency bounds the transfers of DownloadAll; zero or negative selects
// DefaultConcurrency.
Concurrency int
}
Options configures Download and DownloadAll. The zero value is valid.
type Request ¶
type Request struct {
// URL is the source.
URL string
// Dest is the final path. The data is written to Dest+".part" and renamed
// on success, so Dest never holds a partial file. The directory must exist.
Dest string
// Checksum, when set, is verified before the rename. The hash also covers
// the prefix of a resumed partial file.
Checksum *Checksum
// MaxBytes caps the file size; zero means no cap. A larger file fails with
// ErrTooLarge, from the announced length when there is one and from the
// stream otherwise.
MaxBytes int64
// Progress, when set, is called after each chunk with the bytes on disk so
// far (a resumed prefix included) and the expected total, -1 when unknown.
// It runs on the transfer's goroutine, so it must be quick and, with
// DownloadAll, safe to call concurrently with other requests' callbacks.
Progress func(done, total int64)
}
Request describes one file to download.
type Result ¶
Result is the outcome of one request of DownloadAll.
func DownloadAll ¶
DownloadAll runs the requests with at most opts.Concurrency transfers at a time and returns one Result per request, in the order given. A failure does not stop the others; cancelling ctx fails the ones not yet finished. Requests must not share a Dest.
type StatusError ¶
type StatusError = httpclient.HTTPStatusError
StatusError is returned for a non-2xx answer. It is httpclient.HTTPStatusError, so httpclient.IsRetryable classifies it: 408, 429 and 5xx are retried, other 4xx are not.