Skip to content

File Download

Package-Level Download Functions

Download

go
func Download(ctx context.Context, url string, cfg *DownloadConfig, options ...RequestOption) (*DownloadResult, error)

Downloads a file using the default client. Download is the single canonical download entry point shared across the package-level function, the Client interface, and DomainClient, replacing the previous variant matrix with a single signature. cfg must not be nil, and cfg.FilePath must be set (otherwise ErrEmptyFilePath is returned).

go
cfg := httpc.DefaultDownloadConfig()
cfg.FilePath = "/tmp/file.zip"
cfg.Overwrite = true
cfg.ResumeDownload = true

result, err := httpc.Download(context.Background(), url, cfg)

DownloadConfig

go
type DownloadConfig struct {
    FilePath          string
    ProgressCallback  DownloadProgressCallback
    Overwrite         bool
    ResumeDownload    bool
    Checksum          string
    ChecksumAlgorithm ChecksumAlgorithm
}

func DefaultDownloadConfig() *DownloadConfig
FieldTypeDefaultDescription
FilePathstring-Save path (required)
ProgressCallbackDownloadProgressCallbacknilProgress callback function
OverwriteboolfalseOverwrite existing file
ResumeDownloadboolfalseEnable resumable download
Checksumstring""Expected checksum value
ChecksumAlgorithmChecksumAlgorithm"sha256"Checksum algorithm

DownloadProgressCallback

go
type DownloadProgressCallback func(downloaded, total int64, speed float64)
ParameterTypeDescription
downloadedint64Bytes downloaded
totalint64Total bytes (-1 if unknown)
speedfloat64Current speed (bytes/second)
go
cfg.ProgressCallback = func(downloaded, total int64, speed float64) {
    pct := float64(downloaded) / float64(total) * 100
    fmt.Printf("\r%.1f%% (%s)", pct, httpc.FormatSpeed(speed))
}

DownloadResult

go
type DownloadResult struct {
    FilePath        string
    BytesWritten    int64
    Duration        time.Duration
    AverageSpeed    float64
    StatusCode      int
    ContentLength   int64
    Resumed         bool
    ResponseCookies []*http.Cookie
    ActualChecksum  string
    Proto           string
    ResponseHeaders http.Header
    RequestURL      string
    RequestMethod   string
    RequestHeaders  http.Header
}
FieldTypeDescription
FilePathstringFile save path
BytesWrittenint64Bytes written
Durationtime.DurationDownload duration
AverageSpeedfloat64Average speed (bytes/second)
StatusCodeintHTTP status code
ContentLengthint64Content-Length header value
ResumedboolWhether completed via resume
ResponseCookies[]*http.CookieResponse cookies
ActualChecksumstringActually computed checksum
ProtostringHTTP protocol version (e.g. "HTTP/1.1", "HTTP/2.0")
ResponseHeadershttp.HeaderResponse headers
RequestURLstringActual request URL
RequestMethodstringRequest HTTP method
RequestHeadershttp.HeaderRequest headers
go
fmt.Printf("Download complete: %s, duration %v, average speed %s\n",
    httpc.FormatBytes(result.BytesWritten),
    result.Duration,
    httpc.FormatSpeed(result.AverageSpeed),
)

TIP

Use FormatBytes and FormatSpeed for human-readable byte and speed strings, avoiding manual 1024-step unit conversion.

Checksum Verification

ChecksumAlgorithm

go
type ChecksumAlgorithm string

Download file integrity verification algorithm.

ConstantValueDescription
ChecksumSHA256"sha256"SHA-256 hash algorithm

Usage Example

go
cfg := httpc.DefaultDownloadConfig()
cfg.FilePath = "/tmp/package.tar.gz"
cfg.Checksum = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
cfg.ChecksumAlgorithm = httpc.ChecksumSHA256

result, err := httpc.Download(context.Background(), url, cfg)
if err != nil {
    // Automatically returns error and deletes downloaded file on checksum mismatch
    log.Fatal(err)
}
fmt.Println("Checksum:", result.ActualChecksum)

TIP

When Checksum is set, file integrity is automatically verified upon download completion. A failed verification automatically deletes the file and returns an error -- no manual comparison needed.

Security Protection

File downloads include multiple layers of built-in security:

ProtectionDescription
UNC path blockingBlocks \\server\share format paths
Control character filteringBlocks control characters in paths
System path protectionBlocks writing to system directories
Path traversal detectionDetects ../ path traversal
Symlink detectionPrevents symlink attacks
Parent directory checkRecursively checks parent directory symlinks

Resumable Downloads

go
cfg := httpc.DefaultDownloadConfig()
cfg.FilePath = "/tmp/large-file.zip"
cfg.ResumeDownload = true

result, err := httpc.Download(context.Background(), url, cfg)
if result.Resumed {
    fmt.Println("Resumed download complete")
}

Resume mechanism:

  1. Check local file size -> use as Range request offset
  2. Server returns 206 (Partial Content) -> append write
  3. Server returns 416 (Range Not Satisfiable) -> return error
  4. Server returns 200 (Range not supported) -> return error (protect local partial file from being overwritten)

See Also