httpx

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 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 httpx builds the HTTP client every network call goes through: a disk cache with ETag revalidation, retries with backoff, a per-host concurrency and rate limit, and a guard that stops at an exhausted GitHub rate limit.

Index

Constants

View Source
const GitHubAPIHost = "api.github.com"

GitHubAPIHost is the host of the GitHub REST and GraphQL APIs.

View Source
const OSVHost = "api.osv.dev"

OSVHost is the host of the OSV API, whose batch query is a read-only POST.

Variables

View Source
var ErrOffline = errors.New("not in the cache")

ErrOffline is returned for a request that --offline can't answer from the cache.

View Source
var ErrRateLimited = errors.New("rate limit reached")

ErrRateLimited is wrapped by RateLimitError.

Functions

func CATransport

func CATransport(caFile string) (http.RoundTripper, error)

CATransport returns the default transport trusting the PEM certificates in caFile on top of the system pool, for Options.Transport. SSL_CERT_FILE works this way on macOS and Windows too.

func New

func New(o Options) *http.Client

New returns a client that retries, limits and logs every request. Without o.RetryPOST, a POST is retried only when the server refused it with 429 or a Retry-After, so a create is never sent twice.

func TTL

func TTL(age time.Duration) time.Duration

TTL returns how long an entry stays fresh when the newest thing it describes is age old: 1 hour under 7 days, 1 day under 6 months, else 10 days. An unknown (negative) age gets 1 hour.

Types

type AgeFunc

type AgeFunc func(req *http.Request, body []byte) time.Time

AgeFunc returns the newest timestamp in a response body, such as the newest release's publish date, or the zero time when there is none.

type Cache

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

Cache is a disk cache for GET and GraphQL POST responses. It keeps an allowlist of response headers and never stores request headers, so tokens stay out of it.

func NewCache

func NewCache(o CacheOptions) *Cache

NewCache returns a cache. Zero options get defaults.

func (*Cache) Clear

func (c *Cache) Clear() (Removed, error)

Clear deletes every entry.

func (*Cache) Close

func (c *Cache) Close() error

Close releases the decompressor.

func (*Cache) Info

func (c *Cache) Info() (Info, error)

Info counts the entries and their size, and how many are within their TTL.

func (*Cache) LogSummary

func (c *Cache) LogSummary(ctx context.Context)

LogSummary logs the counters at debug level.

func (*Cache) Prune

func (c *Cache) Prune(olderThan time.Duration) (Removed, error)

Prune deletes entries not used for olderThan, unreadable entries, leftover temporary files and entries in an old format. Expired entries stay, since their validators make 304s possible.

func (*Cache) Stats

func (c *Cache) Stats() CacheStats

Stats returns the counters so far.

func (*Cache) Wrap

func (c *Cache) Wrap(next http.RoundTripper) http.RoundTripper

Wrap puts the cache in front of next, for Options.Wrap. A nil cache returns next.

type CacheOptions

type CacheOptions struct {
	Dir         string // entries live in Dir/http; empty turns the cache off
	Mode        Mode
	Clock       func() time.Time
	Logger      *slog.Logger
	TTLOverride map[string]time.Duration // by host; replaces the age-based TTL
	Age         AgeFunc                  // nil means only Last-Modified dates an entry
}

CacheOptions configures NewCache.

type CacheStats

type CacheStats struct {
	Requests    int64 // sent to the network
	NotModified int64 // of Requests, answered 304
	Hits        int64 // answered from the cache without a request
	Stored      int64 // new or replaced entries
}

CacheStats counts what the cache did.

type Info

type Info struct {
	Dir     string `json:"dir"`
	Entries int    `json:"entries"`
	Bytes   int64  `json:"bytes"`
	Fresh   int    `json:"fresh"`
	Stale   int    `json:"stale"`
}

Info describes the cache on disk.

type Limit

type Limit struct {
	Concurrency int     // requests in flight at once
	Rate        float64 // requests per second; 0 means no rate limit
}

Limit is the request budget for one host.

func DefaultLimits

func DefaultLimits() (map[string]Limit, Limit)

DefaultLimits returns the per-host limits: 8 concurrent requests to the GitHub API, 4 elsewhere.

type Mode

type Mode int

Mode says how the cache answers requests.

const (
	ModeDefault Mode = iota // serve fresh entries, revalidate stale ones
	ModeOffline             // serve any entry, never touch the network
	ModeRefresh             // revalidate every GET and refetch every POST
	ModeNoCache             // neither read nor write the cache
)

Cache modes, one per flag.

type Options

type Options struct {
	Logger       *slog.Logger
	Transport    http.RoundTripper // nil means a pooled transport that honours proxy variables
	UserAgent    string
	Limits       map[string]Limit // by host
	Default      Limit            // hosts not in Limits
	RetryMax     int
	RetryWaitMin time.Duration
	RetryWaitMax time.Duration
	Clock        func() time.Time
	RetryPOST    bool                                      // POSTs are reads, such as GraphQL queries, and may be resent
	Wrap         func(http.RoundTripper) http.RoundTripper // outermost layer, such as a cache; nil means none
	// SecretPathHosts are hosts whose URL path is a secret, such as hooks.slack.com; logs show
	// their paths as [redacted].
	SecretPathHosts []string
}

Options configures New.

type RateLimitError

type RateLimitError struct {
	Host  string
	Limit int
	Reset time.Time
}

RateLimitError says that a host refused a request because its rate limit is used up.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Is

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

Is makes errors.Is(err, ErrRateLimited) true.

type Removed

type Removed struct {
	Dir     string `json:"dir"`
	Entries int    `json:"entries"`
	Bytes   int64  `json:"bytes"`
}

Removed says what Cache.Clear or Cache.Prune deleted.

Jump to

Keyboard shortcuts

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