httpkit

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 13 Imported by: 11 modules, 11 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

go-httpkit

Go


HTTP client plumbing: capped requests, typed status and rate-limit errors, Retry-After, redirect policies, and resumable verified file downloads. Package httpkit, module github.com/Rethunk-Tech/go-httpkit.

A program that talks to several sites and downloads large files needs the same few things every time, and each is easy to get subtly wrong: a body read with no size bound, a Retry-After that overflows, an API key that follows a redirect to another host, a download that restarts from zero after a dropped connection. This module is the one correct copy of each.

Quick start

go get github.com/Rethunk-Tech/go-httpkit

A worked example and the contracts: HUMANS.md.

Features

  • DoCapped reads an answer at most N bytes and turns every other status into a *StatusError that errors.Is matches against ErrNotFound and ErrRateLimited.
  • RetryAfter reads both header forms and refuses values that would overflow a Duration.
  • NetReason classifies a failed request as DNS, connection refused (including Windows WSAECONNREFUSED), timeout, or other.
  • NoDowngrade, SameOrigin and NoFollow keep credentials where they belong; WithRedirect adds one to a client without losing the client's own.
  • Transport sets a default User-Agent and reports every round trip.
  • download.File resumes, verifies and size-limits a download, checks an optional Options.Digest (sha256, sha512 or md5 in algo:hex form), fails a stalled body with ErrIdle, and shares one bandwidth Limiter across downloads.
  • download.RangeReader reads a remote file's parts through ranged GETs.

Documentation

Doc Audience
HUMANS.md Running and using the package
AGENTS.md Internals, invariants, and why
CONTRIBUTING.md Process — commits, tests, docs
SECURITY.md Vulnerability disclosure
CHANGELOG.md Release notes

License

MIT — see LICENSE. © 2026 Rethunk.Tech, LLC.

Documentation

Overview

Package httpkit is the HTTP client plumbing a program needs once it talks to more than one site: a size-capped request, typed status and rate-limit errors, one Retry-After reader, redirect policies that keep credentials with their origin, and a Transport that sets a default User-Agent and reports every round trip.

Resumable file downloads live in the download subpackage.

Index

Constants

View Source
const DefaultJSONLimit = 16 << 20

DefaultJSONLimit is the body cap DoJSON applies when JSONOptions.Limit is zero.

View Source
const DefaultTimeout = 5 * time.Minute

DefaultTimeout bounds a whole request, body included, for a nil client: http.DefaultClient has none, so a server that stalls a body would hold the caller forever.

Variables

View Source
var (
	// ErrNotFound is matched by a 404 *StatusError.
	ErrNotFound = errors.New("not found")
	// ErrRateLimited is matched by a 429 *StatusError and by every *RateLimitError.
	ErrRateLimited = errors.New("rate limited")
)

Functions

func DoCapped

func DoCapped(hc *http.Client, req *http.Request, limit int64, check func(*http.Response) error) ([]byte, error)

DoCapped sends req with hc (nil means a client with DefaultTimeout) and returns the body of a 200 answer, at most limit bytes. check (nil means none) runs on every response before the status test; a non-nil error from it is returned after the body is closed. Any other status is a *StatusError; a body over limit is safefs.ErrTooLarge. The body is always closed.

func DoJSON added in v0.2.0

func DoJSON(hc *http.Client, req *http.Request, out any, o JSONOptions) error

DoJSON sends req with hc (nil means a client with DefaultTimeout) and decodes a 200 answer's JSON body into out. A 429 is a *RateLimitError carrying the Retry-After reset, any other status a *StatusError, a body over the limit safefs.ErrTooLarge, and malformed JSON an error wrapping the decoder's. Accept is set to application/json when req names none.

func NoDowngrade

func NoDowngrade(req *http.Request, via []*http.Request) error

NoDowngrade refuses a redirect from https to any other scheme: net/http keeps the Authorization header across a same-host redirect, scheme change included. A first hop that is not https may redirect freely. A redirect to another host loses every credential-looking header (see StripCrossHost).

func NoFollow

func NoFollow(*http.Request, []*http.Request) error

NoFollow returns the redirect answer itself instead of following it.

func RedactError added in v0.2.0

func RedactError(err error) error

RedactError returns err with the URL inside a *url.Error (what net/http wraps a failed request in) redacted by RedactURL.

func RedactURL added in v0.2.0

func RedactURL(raw string) string

RedactURL is raw without its query, fragment and userinfo: a query often carries a signature or an API key, and none of it belongs in an error text or a log.

func RetryAfter

func RetryAfter(v string) (at time.Time, ok bool)

RetryAfter reads a Retry-After value (RFC 9110 section 10.2.3): delta-seconds from now, or an HTTP-date. ok is false when v is empty, unparseable, "0" or negative, or more than 365 days of seconds (so the Duration cannot overflow). A past HTTP-date is returned as is; the caller decides what a reset not after now means.

func SameOrigin

func SameOrigin(req *http.Request, via []*http.Request) error

SameOrigin refuses a redirect to another scheme or host than the first request's, so a header such as an API key stays with its origin.

func StripCrossHost added in v0.2.0

func StripCrossHost(names ...string) func(*http.Request, []*http.Request) error

StripCrossHost returns a redirect policy that deletes the named headers, and every header whose name looks like a credential (it holds auth, key, token, secret, cookie, session, credential or password), from a request redirected to a host other than the first request's, or from https to plain http, which would send them in clear text. Once any hop has left that origin they stay stripped for the rest of the chain, as net/http does. It never refuses a redirect.

func WithRedirect

func WithRedirect(hc *http.Client, policy func(*http.Request, []*http.Request) error) *http.Client

WithRedirect returns a shallow copy of hc (nil means a client with DefaultTimeout) whose CheckRedirect runs hc's own policy first, when it has one, and then policy. hc is never modified. A nil hc gets a client with DefaultTimeout.

Types

type JSONOptions added in v0.2.0

type JSONOptions struct {
	// Limit caps the body read, in bytes; zero means DefaultJSONLimit.
	Limit int64
	// Check runs on every response before the status test, ahead of the 429 test, so a caller can claim any
	// status itself (a 403 that means "rate limited" for one API and "not allowed" for another). A non-nil error
	// is returned as is.
	Check func(*http.Response) error
}

JSONOptions tunes DoJSON. The zero value is valid.

type RateLimitError

type RateLimitError struct{ Reset time.Time }

RateLimitError is a server refusing calls until Reset (zero when it did not say).

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Is

func (e *RateLimitError) Is(target error) bool

Is matches ErrRateLimited.

type Reason added in v0.3.0

type Reason string

Reason is why a request did not reach the host.

const (
	// ReasonDNS is a name that did not resolve.
	ReasonDNS Reason = "dns"
	// ReasonTimeout is a deadline, a connect timeout, or a net.Error that timed out.
	ReasonTimeout Reason = "timeout"
	// ReasonRefused is a connect the host rejected, including Windows WSAECONNREFUSED.
	ReasonRefused Reason = "refused"
	// ReasonOther is any other failure, including a nil error.
	ReasonOther Reason = "other"
)

func NetReason added in v0.3.0

func NetReason(err error) Reason

NetReason reports why a request did not reach the host: a name that did not resolve, a connect the host refused (including Windows WSAECONNREFUSED), a timeout (a deadline, ETIMEDOUT / WSAETIMEDOUT, or a net.Error that timed out), or ReasonOther.

type StatusError

type StatusError struct {
	Code   int
	Status string // resp.Status, e.g. "502 Bad Gateway".
}

StatusError is an answer whose status the caller did not accept.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Is

func (e *StatusError) Is(target error) bool

Is matches ErrNotFound for a 404 and ErrRateLimited for a 429.

type Transport

type Transport struct {
	Base      http.RoundTripper // Nil means http.DefaultTransport.
	UserAgent string            // Set only when the request has none.
	// OnResult sees every round trip's response or transport error; nil means none. It must not read resp.Body.
	OnResult func(req *http.Request, resp *http.Response, err error)
}

Transport sets a default User-Agent and reports every round trip.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections forwards to Base when Base has the method, so http.Client.CloseIdleConnections still works.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip never modifies req: when it sets the User-Agent it does so on req.Clone(req.Context()).

Directories

Path Synopsis
Package download fetches large files over flaky links: a resumable, verified, throttled File, and a RangeReader that reads a remote file's parts without downloading all of it.
Package download fetches large files over flaky links: a resumable, verified, throttled File, and a RangeReader that reads a remote file's parts without downloading all of it.

Jump to

Keyboard shortcuts

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