ratelimit

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package ratelimit provides an http.RoundTripper that respects an API's rate limit headers. It reads X-RateLimit-Remaining/Reset and Retry-After from responses and, once the remaining quota reaches zero, short-circuits further requests until the reset time rather than hammering a limit that is already exhausted. A rate-limited request yields a typed *Error carrying the reset time, so callers can fail loud with a clear message.

It composes beneath the httpcache transport (cache outermost), so cache hits never consume rate-limit budget.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	Reset time.Time
}

Error reports that a request was refused because the rate limit is exhausted. Reset is when the limit is expected to replenish (zero if unknown).

func (*Error) Error

func (e *Error) Error() string

type Headers

type Headers struct {
	Remaining  string
	Reset      string
	ResetKind  ResetKind
	RetryAfter string
}

Headers names the rate-limit headers for a provider. The parsing logic is the same everywhere; only the names - and whether the reset is an absolute epoch or a delta - differ, so a provider configures those and nothing more. An empty RetryAfter disables Retry-After handling.

type Option

type Option func(*Transport)

Option configures a Transport.

func WithClock

func WithClock(now func() time.Time) Option

WithClock overrides the time source, for tests.

type ResetKind

type ResetKind int

ResetKind says how a reset header value is interpreted.

const (
	ResetEpoch ResetKind = iota // Unix seconds (e.g. GitHub X-RateLimit-Reset)
	ResetDelta                  // seconds from now (e.g. the IETF draft RateLimit-Reset)
)

type Transport

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

Transport is a rate-limit-aware http.RoundTripper. It reads the configured Headers from each response and, once the quota is spent, refuses further requests until the reset time rather than hammering the limit.

func New

func New(base http.RoundTripper, headers Headers, opts ...Option) *Transport

New wraps base with rate-limit awareness using the given header names. A nil base uses http.DefaultTransport.

func (*Transport) RoundTrip

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

RoundTrip implements http.RoundTripper. It refuses a request up front when the quota is known to be spent, otherwise forwards it, records the limit state the response reports, and converts a rate-limited response into an Error.

Jump to

Keyboard shortcuts

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