httpclient

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 17 Imported by: 2 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.

Documentation

Overview

Package httpclient fetches small and large HTTP resources for repository clients: every body is size-capped, transient failures are retried with jittered exponential backoff, and files are written atomically.

A Client owns one tuned connection pool and one retry policy, both set through Options; share one Client across goroutines. Nothing is configured through package-level state.

Retry classification is exposed as IsRetryable: transport errors, truncated bodies and HTTP 408, 429 and 5xx are retried; 404, certificate failures, size-cap violations and context cancellation are not.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/M0Rf30/pkgformat/httpclient"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		fmt.Fprint(w, "Packages index")
	}))
	defer srv.Close()

	c := httpclient.New(httpclient.Options{
		Retry: httpclient.RetryPolicy{Attempts: 3, BaseDelay: 100 * time.Millisecond},
	})

	body, err := c.FetchBytes(context.Background(), srv.URL, 1<<20)
	fmt.Println(string(body), err)

	// A body over the cap is an error, never a silent truncation.
	_, err = c.FetchBytes(context.Background(), srv.URL, 4)
	fmt.Println(errors.Is(err, httpclient.ErrTooLarge))

}
Output:
Packages index <nil>
true

Index

Examples

Constants

View Source
const (
	DefaultRetryAttempts  = 3
	DefaultRetryBaseDelay = 500 * time.Millisecond
)

Default retry policy values, applied where a RetryPolicy field is zero.

View Source
const DefaultMaxBytes int64 = 2 << 30

DefaultMaxBytes caps individual HTTP responses to 2 GiB when the caller passes no tighter bound. Package indexes are typically a few MB; .deb, .apk and .rpm files top out around a few hundred MB. The cap prevents memory or disk exhaustion from a malicious or buggy mirror serving an unbounded stream.

View Source
const DefaultTimeout = 10 * time.Minute

DefaultTimeout bounds a complete HTTP request (connection, TLS handshake, header read, body read) at 10 minutes. Large downloads over slow links still fit; stalled mirrors fail rather than hang.

Variables

View Source
var ErrBadLength = errors.New("httpclient: transferred length does not match the announced length")

ErrBadLength is returned when a transfer ends with a different number of bytes than the server announced, or when a resumed partial file does not fit the remote file. It is retryable: the fix is to discard the partial data and start over, which a resumable downloader does before it reports the error.

View Source
var ErrTooLarge = errors.New("httpclient: response body exceeds size cap")

ErrTooLarge is returned when a response body exceeds the configured cap.

Functions

func AtomicWrite

func AtomicWrite(destPath string, fn func(io.Writer) error) error

AtomicWrite writes to destPath via a unique temp file in the destination directory, fsync and rename, so readers never see a partial file and concurrent writers to the same destination never share a temp file. fn receives a writer for the temp file; if fn returns an error the temp file is removed.

func CheckStatus

func CheckStatus(resp *http.Response, fetchURL string) error

CheckStatus returns an *HTTPStatusError if resp.StatusCode is not 2xx. The caller still owns resp.Body.Close().

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether err looks like a transient network failure worth retrying: transport-level errors (DNS, connection reset or refused, timeouts, mid-body EOF) and HTTP 408, 429 and 5xx responses.

A transfer that ended with the wrong length (ErrBadLength) is retryable too: the retry starts from a clean file. Context cancellation, response-size caps and all other HTTP 4xx codes are not retryable: they are definitive answers, not blips.

func LimitedBody

func LimitedBody(resp *http.Response) io.Reader

LimitedBody returns resp.Body capped at DefaultMaxBytes. Reading past the cap fails with ErrTooLarge instead of ending in a silent EOF. The caller still closes resp.Body.

func LimitedBodyN

func LimitedBodyN(resp *http.Response, maxBytes int64) io.Reader

LimitedBodyN is LimitedBody with a caller-supplied cap. A non-positive cap falls back to DefaultMaxBytes.

func UpgradeToHTTPS

func UpgradeToHTTPS(rawURL string) (string, bool)

UpgradeToHTTPS rewrites a plain-http URL to https. It returns ok=false for anything that is not parseable http, including URLs already on https.

It helps recover from networks that reset or drop port-80 connections while leaving 443 untouched: many mirrors serve identical content on both schemes, so escalating after a transient http failure is safe.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client fetches size-capped, retried HTTP resources. It is safe for concurrent use and meant to be shared: it owns one connection pool.

func New

func New(opts Options) *Client

New returns a Client configured by opts.

func (*Client) FetchBytes

func (c *Client) FetchBytes(ctx context.Context, rawURL string, maxBytes int64) ([]byte, error)

FetchBytes downloads rawURL and returns the body, capped at maxBytes; a body over the cap fails with ErrTooLarge. A non-positive maxBytes falls back to DefaultMaxBytes. Transient failures are retried per the client's RetryPolicy.

func (*Client) FetchBytesConditional

func (c *Client) FetchBytesConditional(
	ctx context.Context,
	rawURL string,
	maxBytes int64,
	ifModSince time.Time,
) (body []byte, notModified bool, err error)

FetchBytesConditional is like FetchBytes but sends If-Modified-Since when ifModSince is non-zero. On HTTP 304 it returns (nil, true, nil) so the caller can use its on-disk copy. On 200 it returns (data, false, nil). On any other outcome it returns (nil, false, err).

It is the warm-cache primitive that lets a repository client skip re-downloading metadata that has not changed on the server. Transient failures are retried per the client's RetryPolicy.

func (*Client) FetchToFile

func (c *Client) FetchToFile(ctx context.Context, rawURL, destPath string, maxBytes int64) error

FetchToFile downloads rawURL and writes it atomically to destPath, capped at maxBytes. Content-Length is checked as a cheap preflight when available. A non-positive maxBytes falls back to DefaultMaxBytes. Transient failures are retried per the client's RetryPolicy; the atomic temp-file and rename write guarantees a failed attempt leaves no partial file.

func (*Client) HTTP

func (c *Client) HTTP() *http.Client

HTTP returns the underlying *http.Client, for callers that need to issue their own requests over the same connection pool and timeout.

func (*Client) WithRetry

func (c *Client) WithRetry(ctx context.Context, label string, fn func() error) error

WithRetry runs fn until it succeeds, fails with a non-retryable error, or the client's retry budget is exhausted. label identifies the fetch in retry logs (typically the URL). The last error is returned verbatim so callers can still classify it (errors.As on HTTPStatusError, and so on).

Between attempts WithRetry sleeps an exponentially growing delay with ±25% jitter so concurrent workers hitting the same flaky mirror do not retry in lockstep; cancelling ctx ends the wait.

fn must be safe to re-run from scratch: the Fetch methods re-issue the full request and rewrite their output atomically, so a half-read body from a failed attempt is never observable.

func (*Client) WithRetryPolicy

func (c *Client) WithRetryPolicy(p RetryPolicy) *Client

WithRetryPolicy returns a Client that shares c's connection pool, timeout, user agent and logger but retries according to p.

type HTTPStatusError

type HTTPStatusError struct {
	Code int
	URL  string
}

HTTPStatusError is returned by CheckStatus when the response is not 2xx. Callers can use errors.As to extract the status code without parsing the Error() string.

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

Error returns the error message for HTTPStatusError.

func (*HTTPStatusError) IsClientError

func (e *HTTPStatusError) IsClientError() bool

IsClientError reports whether the status is in the 4xx range. Useful for classifying transient repository failures (auth, rate limit, not found) as non-fatal against systemic failures (network, 5xx, disk full).

type Options

type Options struct {
	// HTTPClient, when set, is used as is and Timeout and Transport are
	// ignored. Leave nil to get a client tuned for metadata-heavy workloads
	// (many small fetches against a handful of mirrors).
	HTTPClient *http.Client
	// Transport replaces the built-in tuned transport.
	Transport http.RoundTripper
	// Timeout bounds one complete request; zero selects DefaultTimeout and a
	// negative value disables the bound (the request context governs).
	Timeout time.Duration
	// Retry is the transient-failure policy of the Fetch methods.
	Retry RetryPolicy
	// UserAgent, when non-empty, is sent with every request the Client builds.
	UserAgent string
	// Logger receives one warning per retried failure. Nil is silent.
	Logger *slog.Logger
}

Options configures a Client. The zero value is valid.

type RetryPolicy

type RetryPolicy struct {
	// Attempts is the total number of tries, including the first. Zero selects
	// DefaultRetryAttempts; 1 disables retrying.
	Attempts int
	// BaseDelay is the first backoff interval, doubled on every further retry
	// and jittered by ±25%. Zero selects DefaultRetryBaseDelay; a negative
	// value retries immediately.
	BaseDelay time.Duration
}

RetryPolicy controls how a logical fetch is retried on transient failures. The zero value selects the defaults.

Jump to

Keyboard shortcuts

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