godownload

package module
v0.0.0-...-a5a9674 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

godownload

CI Go Reference Go Report Card codecov Release

A Go download manager for agents and humans: resumable and multi-segment downloads, checksum verification, mirrors, rate limiting, HuggingFace model fetching — as a library and a single-binary CLI with a JSON report for tool-calls.

Why godownload

Feature godownload aria2c wget curl
Resume on failure (.part) ✓ ✓ (-c) ✓ (-c) ✓ (-C -)
Checksum before the file is visible ✓ (md5/sha1/sha256/sha512) ✓ (--checksum) — —
Parallel ranged segments ✓ ✓ — —
Rate limiting ✓ ✓ ✓ ✓
Declarative manifest with mirrors ✓ (YAML) ✓ (Metalink) — —
ETag freshness check (no re-download) ✓ (--no-stale) — — —
Bulk HuggingFace model fetch ✓ (--hf) — — —
Machine-readable JSON report ✓ (--json) — — —
Library API (Go) ✓ RPC only — —
Static single binary, zero deps ✓ — ✓ —
Atomic writes ✓ — — —

Download results and per-download callbacks (OnDone, OnProgress) are available to library users (see Download results).

Agent workflow

Download a model and get a stable JSON report back — for agent tool-calls and scripts:

godownload --hf teneso/llama-tiny --outdir ./llama-tiny --json
# repeat runs transfer nothing until the repository changes on the server

Install

go get github.com/saromanov/godownload
go install github.com/saromanov/godownload/cmd/godownload@latest

macOS via Homebrew:

brew install saromanov/tap/godownload

Usage

Download a file (the name is taken from the URL):

package main

import godownload "github.com/saromanov/godownload"

func main() {
    gd := godownload.GoDownload{}
    if err := gd.Download("http://arxiv.org/pdf/1206.5538v3.pdf", nil); err != nil {
        panic(err)
    }
}

With a specific output file:

gd := godownload.GoDownload{}
err := gd.Download("http://arxiv.org/pdf/1206.5538v3.pdf", &godownload.Options{Outpath: "fun.pdf"})

Download multiple files in parallel:

gd := godownload.GoDownload{}
err := gd.DownloadMany([]*godownload.Options{
    {URL: "https://example.com/a.pdf", Outpath: "a.pdf"},
    {URL: "https://example.com/b.pdf", Outpath: "b.pdf"},
})

Download by links listed in a file:

gd := godownload.GoDownload{}
err := gd.FromFile("links.txt")

Download an HTML page:

gd := godownload.GoDownload{}
err := gd.Download("https://example.com", &godownload.Options{Page: true, Outpath: "index.html"})

Custom timeout and retries:

gd := godownload.GoDownload{Timeout: 30 * time.Second}
err := gd.Download("https://example.com/file.zip", &godownload.Options{Retry: 3})

API

GoDownload

Global settings (all optional):

Field Description
Overwrite Overwrite a file with the same name
Alwaysnew Always create a new file (file_1, file_2, ...)
UserAgent User-Agent for HTTP requests
Retry Number of retry attempts on network errors and 5xx responses
Auth Basic authentication in the username:password format
Archive Archive format for the downloaded file (zip)
Configpath Path to a YAML config
Outdir Directory for downloaded files
Timeout HTTP request timeout (no timeout by default)
Logger Custom logger (nil — standard log)
Quiet Disable all logging output
HTTPClient Custom http.Client
OnProgress Progress callback (see below)
Checksum Checksum verification (see below)
RateLimit Download speed cap in bytes per second
Segments Number of parallel ranged segments
NoStale Skip the download when the file is up to date (see below)
Options

Per-download settings (the same fields where applicable) plus:

Field Description
URL URL — needed only for DownloadMany
Page Download an HTML page instead of a file
Outpath Path of the downloaded file

All methods return error. Sentinel errors: ErrFileExists, ErrChecksumMismatch, ErrUnsupportedArchive.

Download results

Every download method has a *Result variant that reports the outcome: DownloadResult, DownloadManyResult, DownloadManySimpleResult, FromFileResult, FromManifestResult — all take context.Context and return Result{URL, Path, Size, Bytes, Segments, ChecksumVerified, Duration}. Alternatively, GoDownload.OnDone (or Options.OnDone) is called once per successfully downloaded file:

gd := godownload.GoDownload{}
res, err := gd.DownloadResult(ctx, "https://example.com/model.bin",
    &godownload.Options{Checksum: "sha256:...", Segments: 8})
if err != nil {
    return err
}
fmt.Printf("saved to %s (%d bytes, %d segments, verified: %v, took %s)\n",
    res.Path, res.Size, res.Segments, res.ChecksumVerified, res.Duration)

DownloadManyResult returns the results of successful downloads together with an aggregated error on partial failure.

v2.0: methods no longer terminate the process via log.Fatal/panic and return error instead. This is a breaking change compared to v1.

Reliability features

Atomic writes, resume and checksum verification are always on for file downloads (Options.Checksum is opt-in):

  • The file lands under its final name only after a successful write (atomic rename from file.part)
  • Interrupted downloads resume via Range requests (file.part is kept on failure)
  • ErrFileExists, ErrChecksumMismatch, ErrUnsupportedArchive are checkable with errors.Is

Progress, throttling and multi-segment downloads:

gd := godownload.GoDownload{Timeout: 30 * time.Second}
err := gd.Download("https://example.com/big.iso", &godownload.Options{
    Outpath:   "big.iso",
    Segments:  8,                // parallel ranged segments
    RateLimit: 10 * 1024 * 1024, // 10 MiB/s
    Checksum:  "sha256:...",     // verify before the file becomes visible
    OnProgress: func(transferred, total int64) {
        fmt.Printf("\r%d / %d", transferred, total)
    },
})

Declarative downloads from a YAML manifest with mirrors:

- url: https://example.com/model.bin
  out: model.bin
  checksum: sha256:b5bb9d80...
  segments: 8
  mirrors:
    - https://mirror.example.com/model.bin
- url: https://example.com/data.csv
  out: data.csv
  retry: 5
gd := godownload.GoDownload{}
if err := gd.FromManifest("downloads.yaml"); err != nil {
    // ...
}

Freshness check (NoStale)

With NoStale: true the download is skipped when the server reports the file unchanged since the last download of the same output file. After each download the validator headers (ETag, Last-Modified) are stored in a sidecar file <outpath>.gd-meta; the next download sends a conditional request (If-None-Match / If-Modified-Since) and keeps the existing file on a 304 Not Modified:

gd := godownload.GoDownload{}
res, err := gd.DownloadResult(ctx, "https://example.com/model.bin",
    &godownload.Options{Outpath: "model.bin", NoStale: true})
if err != nil {
    return err
}
if res.CacheHit {
    fmt.Println("already up to date:", res.Path)
}

An existing output file is not rejected with ErrFileExists when NoStale is set: the freshness check decides whether it is re-downloaded. Works with multi-segment downloads (the probe request is conditional) and with the CLI --no-stale flag.

Downloading HuggingFace models

DownloadHF fetches a full model repository (all files, nested paths preserved):

gd := godownload.GoDownload{}
results, err := gd.DownloadHFResult(ctx, "meta-llama/Llama-3.2-1B",
    &godownload.Options{Outpath: "llama-3.2-1b", Segments: 8, NoStale: true})
if err != nil {
    return err
}
for _, r := range results {
    fmt.Printf("%s: %d bytes\n", r.Path, r.Size)
}
  • Files are resolved through https://huggingface.co/<repo>/resolve/main/... (LFS redirects to the CDN are followed automatically)
  • Every file keeps its repository path under Options.Outpath
  • Segments, RateLimit, Retry, NoStale and other options apply per file; NoStale makes repeated runs transfer nothing when the repository is unchanged
  • Options.HFAPIURL points the client to a self-hosted HuggingFace-compatible endpoint (or a test server)

Context support

Every download method has a context-aware variant (DownloadContext, DownloadManyContext, DownloadManySimpleContext, FromFileContext, FromManifestContext). Context cancellation aborts in-flight HTTP requests.

CLI

The repository ships a CLI built on top of the library (see the release workflow for binaries):

godownload [flags] URL...
godownload --manifest downloads.yaml
godownload --from-file links.txt --segments 8 --checksum sha256:...
godownload --hf owner/model --outdir ./models --json

The --json flag prints a machine-readable report for agents and scripts — one object per download (url, path, size, bytes, segments, checksum_verified, cache_hit, duration_ns) plus an error field on failure:

$ godownload --hf meta-llama/Llama-3.2-1B --outdir ./models --json
{
  "downloads": [
    {
      "url": "https://huggingface.co/meta-llama/Llama-3.2-1B/resolve/main/config.json",
      "path": "models/config.json",
      "size": 861,
      "bytes": 861,
      "segments": 1,
      "checksum_verified": false,
      "cache_hit": false,
      "duration_ns": 45231500
    }
  ]
}

Contributing

See CONTRIBUTING.md. Security issues: SECURITY.md.

Documentation

Index

Constants

View Source
const Version = "2.1.1"

Version is the version of the library.

Variables

View Source
var ErrChecksumMismatch = errors.New("checksum mismatch")

ErrChecksumMismatch is returned when the downloaded file does not match the expected checksum

View Source
var ErrEmptyOutpath = errors.New("outpath is not specified")

ErrEmptyOutpath — ошибка, когда для скачивания страницы не задан путь вывода.

View Source
var ErrFileExists = errors.New("file already exists")

ErrFileExists — ошибка, когда целевой файл уже существует, а перезапись запрещена.

View Source
var ErrNoRangeSupport = errors.New("server does not support range requests")

ErrNoRangeSupport is returned when Segments > 1 but the server does not support Range requests

View Source
var ErrUnsupportedArchive = errors.New("unsupported archive format")

ErrUnsupportedArchive — ошибка неподдерживаемого формата архива.

Functions

This section is empty.

Types

type GoDownload

type GoDownload struct {

	//Overwrite provides overwriting file with same name
	Overwrite bool

	//Alwaysnew provides always creating new file.
	// If file with same name exist, create "file_1"
	Alwaysnew bool

	//UserAgent provides setting user agent for http request
	UserAgent string

	//Retry provides number of attempts to download file
	Retry int

	//Authentication before downloading. Auth in the format username:password
	Auth string

	//Specify archive format for downloaded file.
	// Supported values: "zip"
	Archive string

	//OnProgress is called periodically during the download with
	// the number of bytes transferred so far and the total size
	// (0 if the total size is unknown, e.g. chunked responses).
	// Called from the download goroutine; must be cheap or spawn
	// its own goroutine
	OnProgress func(transferred, total int64)

	//Checksum verifies the downloaded file before it becomes visible.
	// Format: "<algorithm>:<hex>", supported algorithms: md5, sha1,
	// sha256, sha512. Example: "sha256:abc123..."
	// An empty value disables verification
	Checksum string

	//RateLimit caps the download speed in bytes per second.
	// Zero means unlimited
	RateLimit int64

	//Segments splits large downloads into this many parallel ranged
	// segments (only when the server supports Range requests).
	// Values < 2 mean a single stream. Default: 1
	Segments int

	//Path to the config file
	Configpath string

	//Directory for downloaded files
	Outdir string

	//Timeout limits the time for the whole request.
	// Zero means no timeout (not recommended)
	Timeout time.Duration

	//Logger is used for all messages of the library.
	// nil means log.Default()
	Logger *log.Logger

	//Quiet disables all logging output
	Quiet bool

	//HTTPClient allows to provide a custom http.Client.
	// If nil, a client with Timeout is used
	HTTPClient *http.Client

	//NoStale skips the download when the server reports the file
	// unchanged since the last download of the same output file
	// (conditional request with If-None-Match / If-Modified-Since
	// based on a sidecar "<outpath>.gd-meta" file). The Result has
	// CacheHit set and Bytes of zero
	NoStale bool

	//OnDone is called once per successfully downloaded file
	// with the outcome of the download (path, size, duration, ...)
	// It is the same Result that the *Result methods return
	OnDone func(Result)
}

GoDownload provides main struct for global config and downloading items

func (*GoDownload) Download

func (gd *GoDownload) Download(path string, opt *Options) error

Download provides downloading of file from path. Instead of terminating the process on error, it returns an error

func (*GoDownload) DownloadContext

func (gd *GoDownload) DownloadContext(ctx context.Context, path string, opt *Options) error

DownloadContext downloads a file from path, honouring ctx cancellation: in-flight HTTP requests are aborted and no file is written after the context is done

func (*GoDownload) DownloadHF

func (gd *GoDownload) DownloadHF(repo string, opt *Options) error

DownloadHF downloads all files of a HuggingFace model repository (https://huggingface.co/<owner>/<name>). Nested paths inside the repository are preserved. The repository files are downloaded concurrently with the global options applied to every file

func (*GoDownload) DownloadHFContext

func (gd *GoDownload) DownloadHFContext(ctx context.Context, repo string, opt *Options) error

DownloadHFContext is the context-aware version of DownloadHF

func (*GoDownload) DownloadHFResult

func (gd *GoDownload) DownloadHFResult(ctx context.Context, repo string, opt *Options) ([]Result, error)

DownloadHFResult is the context-aware DownloadHF reporting results. On partial failure it returns the results of the successful downloads together with the aggregated error

func (*GoDownload) DownloadMany

func (gd *GoDownload) DownloadMany(items []*Options) error

DownloadMany provides downloading several files concurrently. Errors of individual downloads are collected and returned as a single aggregated error

func (*GoDownload) DownloadManyContext

func (gd *GoDownload) DownloadManyContext(ctx context.Context, items []*Options) error

DownloadManyContext downloads several files concurrently, honouring ctx cancellation

func (*GoDownload) DownloadManyResult

func (gd *GoDownload) DownloadManyResult(ctx context.Context, items []*Options) ([]Result, error)

DownloadManyResult is the context-aware DownloadMany reporting results. On partial failure it returns the results of the successful downloads together with the aggregated error

func (*GoDownload) DownloadManySimple

func (gd *GoDownload) DownloadManySimple(items []string) error

DownloadManySimple is identical for DownloadMany, but as arguments is slice of url

func (*GoDownload) DownloadManySimpleContext

func (gd *GoDownload) DownloadManySimpleContext(ctx context.Context, items []string) error

DownloadManySimpleContext is the context-aware version of DownloadManySimple

func (*GoDownload) DownloadManySimpleResult

func (gd *GoDownload) DownloadManySimpleResult(ctx context.Context, items []string) ([]Result, error)

DownloadManySimpleResult is the context-aware DownloadManySimple reporting results

func (*GoDownload) DownloadResult

func (gd *GoDownload) DownloadResult(ctx context.Context, path string, opt *Options) (Result, error)

DownloadResult is the context-aware download that reports the outcome

func (*GoDownload) FromFile

func (gd *GoDownload) FromFile(path string) error

FromFile provides getting links from file and downloading

func (*GoDownload) FromFileContext

func (gd *GoDownload) FromFileContext(ctx context.Context, path string) error

FromFileContext is the context-aware version of FromFile

func (*GoDownload) FromFileResult

func (gd *GoDownload) FromFileResult(ctx context.Context, path string) ([]Result, error)

FromFileResult is the context-aware FromFile reporting results

func (*GoDownload) FromManifest

func (gd *GoDownload) FromManifest(manifestpath string) error

FromManifest downloads all files declared in a YAML manifest:

Items are downloaded concurrently; per-item settings override the global GoDownload config

func (*GoDownload) FromManifestContext

func (gd *GoDownload) FromManifestContext(ctx context.Context, manifestpath string) error

FromManifestContext is the context-aware version of FromManifest

func (*GoDownload) FromManifestResult

func (gd *GoDownload) FromManifestResult(ctx context.Context, manifestpath string) ([]Result, error)

FromManifestResult is the context-aware FromManifest reporting results. On partial failure it returns the results of the successful downloads together with the aggregated error

type ManifestItem

type ManifestItem struct {
	// URL of the file to download (required)
	URL string `yaml:"url"`
	// Out is the output path of the downloaded file (required)
	Out string `yaml:"out"`
	// Checksum in the "<algorithm>:<hex>" format (optional)
	Checksum string `yaml:"checksum,omitempty"`
	// Mirrors is a list of alternative URLs (optional).
	// The first URL that responds is used; the primary URL
	// comes first implicitly
	Mirrors []string `yaml:"mirrors,omitempty"`
	// Retry overrides the global retry count (optional)
	Retry int `yaml:"retry,omitempty"`
	// Segments overrides the global segment count (optional)
	Segments int `yaml:"segments,omitempty"`
	// RateLimit overrides the global rate limit (optional)
	RateLimit int64 `yaml:"rate_limit,omitempty"`
	// Archive overrides the global archive format (optional)
	Archive string `yaml:"archive,omitempty"`
	// Auth overrides the global auth (optional)
	Auth string `yaml:"auth,omitempty"`
}

ManifestItem describes a single download entry in a YAML manifest

type Options

type Options struct {

	// URL parameter needs only for DownloadMany.
	// In the case with Download. This parameter will be ignored
	URL string

	//Download web page instead file
	Page bool

	//Outpath sets the path of the downloaded file
	Outpath string

	//Overwrite provides overwriting file with same name
	Overwrite bool

	//Alwaysnew provides always creating new file.
	// If file with same name exist, create "file_1"
	Alwaysnew bool

	//UserAgent provides setting user agent for http request
	UserAgent string

	//Retry provides number of attempts to download file
	Retry int

	//Authentication before downloading. Auth in the format username:password
	Auth string

	//Specify archive format for downloaded file.
	// Supported values: "zip"
	Archive string

	//OnProgress is called periodically during the download with
	// the number of bytes transferred so far and the total size
	// (0 if the total size is unknown, e.g. chunked responses).
	// Called from the download goroutine; must be cheap or spawn
	// its own goroutine
	OnProgress func(transferred, total int64)

	//Checksum verifies the downloaded file before it becomes visible.
	// Format: "<algorithm>:<hex>", supported algorithms: md5, sha1,
	// sha256, sha512. Example: "sha256:abc123..."
	// An empty value disables verification
	Checksum string

	//RateLimit caps the download speed in bytes per second.
	// Zero means unlimited
	RateLimit int64

	//Segments splits large downloads into this many parallel ranged
	// segments (only when the server supports Range requests).
	// Values < 2 mean a single stream. Default: 1
	Segments int

	//OnDone is called once per successfully downloaded file
	// with the outcome of the download (path, size, duration, ...)
	// It overrides GoDownload.OnDone for this download
	OnDone func(Result)

	//NoStale skips the download when the server reports the file
	// unchanged since the last download of the same output file.
	// It overrides GoDownload.NoStale for this download
	NoStale bool

	//HFAPIURL overrides the HuggingFace base URL for DownloadHF
	// (self-hosted deployments, tests). Empty means
	// https://huggingface.co
	HFAPIURL string
	// contains filtered or unexported fields
}

Options defines attributes for config of GoDownload

type Result

type Result struct {
	// URL is the source the file was downloaded from.
	// For manifest and mirror downloads it is the URL that
	// actually responded successfully
	URL string `json:"url"`

	// Path is the final path of the downloaded file.
	// For archived downloads this is the path of the archive
	Path string `json:"path"`

	// Size is the size of the final file on disk.
	// 0 is reported when the size cannot be determined
	Size int64 `json:"size"`

	// Bytes is the number of bytes transferred over the network.
	// For resumed downloads it may be less than Size
	Bytes int64 `json:"bytes"`

	// Segments is the number of parallel segments used.
	// 1 means a single-stream download
	Segments int `json:"segments"`

	// ChecksumVerified is true when a checksum was requested
	// (Options.Checksum) and the downloaded file passed verification
	ChecksumVerified bool `json:"checksum_verified"`

	// CacheHit is true when the download was skipped because the
	// server reported the file unchanged since the last download
	// (Options.NoStale). Bytes is 0 and Size is the size of the
	// already existing file
	CacheHit bool `json:"cache_hit"`

	// Duration is the wall time the download took
	Duration time.Duration `json:"duration_ns"`
}

Result describes the outcome of a single completed download. It is returned by the *Result methods and passed to OnDone

Directories

Path Synopsis
cmd
godownload command
Command godownload downloads files from URLs or YAML manifests.
Command godownload downloads files from URLs or YAML manifests.
examples
basic command
Basic example: download a file with the default settings.
Basic example: download a file with the default settings.
manifest command
Manifest example: declarative downloads from a YAML file.
Manifest example: declarative downloads from a YAML file.
multi-segment command
Multi-segment example: fast parallel download with progress, throttling and checksum verification.
Multi-segment example: fast parallel download with progress, throttling and checksum verification.
rate-limit command
Rate limit example: throttle the download speed.
Rate limit example: throttle the download speed.
internal
clitest
Package clitest provides helpers for testing the example and CLI binaries of the module.
Package clitest provides helpers for testing the example and CLI binaries of the module.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL