httpx

package
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidOption reports a client option carrying an invalid value,
	// such as a malformed base or proxy URL.
	ErrInvalidOption = errors.New("httpx: invalid option")

	// ErrConflictingOptions reports mutually exclusive client options, such
	// as WithHTTPClient combined with transport-level options.
	ErrConflictingOptions = errors.New("httpx: conflicting options")

	// ErrInvalidRequestURL reports a request URL that cannot be parsed, or a
	// relative URL used on a client that has no base URL.
	ErrInvalidRequestURL = errors.New("httpx: invalid request URL")

	// ErrMissingPathParam reports a ":name" path segment left unresolved
	// because no value was supplied via SetPathParam.
	ErrMissingPathParam = errors.New("httpx: missing path parameter")

	// ErrRequestReused reports a second execution of a single-use Request.
	ErrRequestReused = errors.New("httpx: request already executed")

	// ErrTooManyRedirects reports a call exceeding the redirect cap set via
	// WithMaxRedirects.
	ErrTooManyRedirects = errors.New("httpx: too many redirects")

	// ErrResponseTooLarge reports a response body exceeding the cap set via
	// WithMaxResponseBody.
	ErrResponseTooLarge = errors.New("httpx: response body too large")
)

Functions

This section is empty.

Types

type Client added in v0.39.0

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

Client is an HTTP client for calling one upstream service — construct one per third-party system. A Client is immutable after New and safe for concurrent use; per-call state lives in the Request created by NewRequest.

func New added in v0.39.0

func New(opts ...Option) (*Client, error)

New builds a Client, validating options eagerly: a malformed base or proxy URL and conflicting transport-level options fail construction. The zero-option client is ready to use — no base URL, a 30s call timeout, no retries.

func (*Client) NewRequest added in v0.39.0

func (c *Client) NewRequest() *Request

NewRequest starts a single-use request builder bound to this client.

type Option added in v0.39.0

type Option func(*clientConfig)

Option customizes client construction.

func WithBaseURL added in v0.39.0

func WithBaseURL(baseURL string) Option

WithBaseURL sets the absolute URL every relative request URL joins onto; a request supplying an absolute URL bypasses it.

func WithBasicAuth added in v0.39.0

func WithBasicAuth(username, password string) Option

WithBasicAuth authenticates every request with HTTP Basic credentials. The last authentication option wins, and request-level authentication overrides it.

func WithBearerToken added in v0.39.0

func WithBearerToken(token string) Option

WithBearerToken authenticates every request with a bearer token. The last authentication option wins, and request-level authentication overrides it.

func WithCookieJar added in v0.39.0

func WithCookieJar(jar http.CookieJar) Option

WithCookieJar stores and replays cookies across the client's requests. Incompatible with WithHTTPClient.

func WithHTTPClient added in v0.39.0

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the underlying *http.Client entirely, taking ownership of transport, redirects, and cookies. Incompatible with WithTransport, WithProxy, WithTLSConfig, WithCookieJar, and WithMaxRedirects.

func WithHeader added in v0.39.0

func WithHeader(key, value string) Option

WithHeader adds a default header sent with every request; a request-level header of the same name replaces it.

func WithMaxRedirects added in v0.39.0

func WithMaxRedirects(n int) Option

WithMaxRedirects caps how many redirects a call follows (default 10); zero disables following so a 3xx response is returned as-is. Incompatible with WithHTTPClient.

func WithMaxResponseBody added in v0.39.0

func WithMaxResponseBody(n int64) Option

WithMaxResponseBody caps the buffered response body size in bytes; a larger body fails the call with ErrResponseTooLarge. The default is unbounded.

func WithProxy added in v0.39.0

func WithProxy(proxyURL string) Option

WithProxy routes every request through the given proxy URL. Incompatible with WithTransport and WithHTTPClient.

func WithQuery added in v0.39.0

func WithQuery(key, value string) Option

WithQuery adds a default query parameter sent with every request, such as an API key; a request-level parameter of the same name replaces it.

func WithRequestHook added in v0.39.0

func WithRequestHook(hooks ...RequestHook) Option

WithRequestHook appends hooks run before each request is sent, in registration order.

func WithResponseHook added in v0.39.0

func WithResponseHook(hooks ...ResponseHook) Option

WithResponseHook appends hooks run after each response body is buffered, in registration order.

func WithRetry added in v0.39.0

func WithRetry(cfg RetryConfig) Option

WithRetry enables automatic retries under the given policy; without this option every call makes a single attempt.

func WithTLSConfig added in v0.39.0

func WithTLSConfig(cfg *tls.Config) Option

WithTLSConfig sets the TLS client configuration. Incompatible with WithTransport and WithHTTPClient.

func WithTimeout added in v0.39.0

func WithTimeout(d time.Duration) Option

WithTimeout bounds each whole call, retries included; an earlier context deadline still wins, and Request.SetTimeout overrides the bound per request. Zero removes it. The default is 30s.

func WithTransport added in v0.39.0

func WithTransport(rt http.RoundTripper) Option

WithTransport sets the wire-level transport — the seam for tracing round-trippers, custom dialing, and test doubles. Incompatible with WithProxy, WithTLSConfig, and WithHTTPClient.

type Request added in v0.39.0

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

Request is a single-use request builder created by Client.NewRequest: the Set/Add methods chain, a terminal method (Get, Post, ..., Do) executes the request, and a second execution fails with ErrRequestReused. Builder errors such as a failed body marshal are recorded and surface at the terminal method, so a chain needs no mid-flight error checks.

func (*Request) AddFile added in v0.39.0

func (r *Request) AddFile(field, path string) *Request

AddFile attaches the file at path as a multipart part named field, using the path's base name as the file name; the file is read when the request executes.

func (*Request) AddFileReader added in v0.39.0

func (r *Request) AddFileReader(field, filename string, reader io.Reader) *Request

AddFileReader attaches a multipart file part read from reader; the reader is drained into the buffered body when the request executes.

func (*Request) AddFormField added in v0.39.0

func (r *Request) AddFormField(key, value string) *Request

AddFormField appends a form field value, allowing repeated names.

func (*Request) AddHeader added in v0.39.0

func (r *Request) AddHeader(key, value string) *Request

AddHeader appends a header value, keeping previously added ones.

func (*Request) AddQuery added in v0.39.0

func (r *Request) AddQuery(key, value string) *Request

AddQuery appends a query parameter value, keeping previously added ones.

func (*Request) Body added in v0.39.0

func (r *Request) Body() []byte

Body returns the buffered request body; nil when there is none or when the body streams from a reader.

func (*Request) Context added in v0.39.0

func (r *Request) Context() context.Context

Context returns the execution context while the request runs; context.Background() otherwise.

func (*Request) Delete added in v0.39.0

func (r *Request) Delete(ctx context.Context, url string) (*Response, error)

Delete executes the request as an HTTP DELETE against url.

func (*Request) Do added in v0.39.0

func (r *Request) Do(ctx context.Context, method, url string) (*Response, error)

Do executes the request with an arbitrary method; every terminal verb funnels through it.

func (*Request) Get added in v0.39.0

func (r *Request) Get(ctx context.Context, url string) (*Response, error)

Get executes the request as an HTTP GET against url, resolved against the client's base URL when relative.

func (*Request) Head added in v0.39.0

func (r *Request) Head(ctx context.Context, url string) (*Response, error)

Head executes the request as an HTTP HEAD against url.

func (*Request) Header added in v0.39.0

func (r *Request) Header(key string) string

Header returns the first value of the named request header.

func (*Request) Headers added in v0.39.0

func (r *Request) Headers() http.Header

Headers returns the request headers. During a RequestHook they are the final outgoing headers and may still be mutated.

func (*Request) Method added in v0.39.0

func (r *Request) Method() string

Method returns the HTTP method; empty until a terminal method runs.

func (*Request) Options added in v0.39.0

func (r *Request) Options(ctx context.Context, url string) (*Response, error)

Options executes the request as an HTTP OPTIONS against url.

func (*Request) Patch added in v0.39.0

func (r *Request) Patch(ctx context.Context, url string) (*Response, error)

Patch executes the request as an HTTP PATCH against url.

func (*Request) Post added in v0.39.0

func (r *Request) Post(ctx context.Context, url string) (*Response, error)

Post executes the request as an HTTP POST against url.

func (*Request) Put added in v0.39.0

func (r *Request) Put(ctx context.Context, url string) (*Response, error)

Put executes the request as an HTTP PUT against url.

func (*Request) SetBasicAuth added in v0.39.0

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth authenticates this request with HTTP Basic credentials, overriding client-level authentication; the last authentication setter wins.

func (*Request) SetBearerToken added in v0.39.0

func (r *Request) SetBearerToken(token string) *Request

SetBearerToken authenticates this request with a bearer token, overriding client-level authentication; the last authentication setter wins.

func (*Request) SetBody added in v0.39.0

func (r *Request) SetBody(body []byte, contentType string) *Request

SetBody sets a raw request body with an explicit content type; a Content-Type header set on the request or client still takes precedence.

func (*Request) SetBodyReader added in v0.39.0

func (r *Request) SetBodyReader(reader io.Reader, contentType string) *Request

SetBodyReader streams the request body from reader with an explicit content type. A streamed body cannot be replayed, so the request is never retried.

func (*Request) SetCookie added in v0.39.0

func (r *Request) SetCookie(name, value string) *Request

SetCookie sends a cookie with the request, replacing a same-named one.

func (*Request) SetForm added in v0.39.0

func (r *Request) SetForm(m map[string]string) *Request

SetForm sets each form field in m. Fields alone are sent as application/x-www-form-urlencoded; attaching any file upgrades the body to multipart/form-data with the fields as parts.

func (*Request) SetHeader added in v0.39.0

func (r *Request) SetHeader(key, value string) *Request

SetHeader sets a header, replacing a client default or previously set value of the same name.

func (*Request) SetHeaders added in v0.39.0

func (r *Request) SetHeaders(h map[string]string) *Request

SetHeaders sets each header in h.

func (*Request) SetJSON added in v0.39.0

func (r *Request) SetJSON(v any) *Request

SetJSON marshals v into a JSON request body and sets the Content-Type. Body setters overwrite one another: the last one wins.

func (*Request) SetPathParam added in v0.39.0

func (r *Request) SetPathParam(key, value string) *Request

SetPathParam supplies the value for a ":name" segment of the request URL — the same template syntax as the server-side routes. The value is URL-escaped; a ":name" segment with no value fails the call with ErrMissingPathParam.

func (*Request) SetPathParams added in v0.39.0

func (r *Request) SetPathParams(m map[string]string) *Request

SetPathParams supplies the value for each ":name" segment in m.

func (*Request) SetQueries added in v0.39.0

func (r *Request) SetQueries(m map[string]string) *Request

SetQueries sets each query parameter in m.

func (*Request) SetQuery added in v0.39.0

func (r *Request) SetQuery(key, value string) *Request

SetQuery sets a query parameter, replacing a client default, URL-carried, or previously set value of the same name.

func (*Request) SetTimeout added in v0.39.0

func (r *Request) SetTimeout(d time.Duration) *Request

SetTimeout overrides the client's call timeout for this request; zero removes the bound entirely.

func (*Request) SetXML added in v0.39.0

func (r *Request) SetXML(v any) *Request

SetXML marshals v into an XML request body and sets the Content-Type.

func (*Request) URL added in v0.39.0

func (r *Request) URL() string

URL returns the fully resolved request URL — base joined, path parameters substituted, query merged; empty until a terminal method runs.

type RequestHook added in v0.39.0

type RequestHook func(req *Request) error

RequestHook runs after a request is fully built — URL resolved, body marshaled — and before it is sent, so it can read the final shape and still adjust headers: the hook point for signing, audit, and logging. A returned error aborts the call.

type Response added in v0.39.0

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

Response is the fully buffered outcome of a call: the body has been read and the connection released, so a Response is inert data that is safe to keep and share.

func (*Response) Attempts added in v0.39.0

func (r *Response) Attempts() int

Attempts returns how many attempts the call made; 1 unless retries ran.

func (*Response) Body added in v0.39.0

func (r *Response) Body() []byte

Body returns the buffered response body.

func (*Response) Cookies added in v0.39.0

func (r *Response) Cookies() []*http.Cookie

Cookies returns the cookies the response sets.

func (*Response) Duration added in v0.39.0

func (r *Response) Duration() time.Duration

Duration returns the wall time of the whole call, retries included.

func (*Response) Header added in v0.39.0

func (r *Response) Header(key string) string

Header returns the first value of the named response header.

func (*Response) Headers added in v0.39.0

func (r *Response) Headers() http.Header

Headers returns all response headers.

func (*Response) IsSuccess added in v0.39.0

func (r *Response) IsSuccess() bool

IsSuccess reports whether the status code is in the 2xx range. A non-2xx response is not an error — inspect it through this and StatusCode.

func (*Response) JSON added in v0.39.0

func (r *Response) JSON(v any) error

JSON unmarshals the response body as JSON into v.

func (*Response) Request added in v0.39.0

func (r *Response) Request() *Request

Request returns the request that produced this response.

func (*Response) Status added in v0.39.0

func (r *Response) Status() string

Status returns the full status line, e.g. "200 OK".

func (*Response) StatusCode added in v0.39.0

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code.

func (*Response) String added in v0.39.0

func (r *Response) String() string

String returns the response body as a string.

func (*Response) XML added in v0.39.0

func (r *Response) XML(v any) error

XML unmarshals the response body as XML into v.

type ResponseHook added in v0.39.0

type ResponseHook func(resp *Response) error

ResponseHook runs after a response arrives and its body is buffered. A returned error fails the call.

type RetryConfig added in v0.39.0

type RetryConfig struct {
	// MaxAttempts is the total number of attempts, the first call included.
	// Default 3.
	MaxAttempts int

	// InitialBackoff is the base delay before the first retry; every further
	// retry doubles it, with full jitter applied. Default 100ms.
	InitialBackoff time.Duration

	// MaxBackoff caps the delay between attempts, a server-sent Retry-After
	// included. Default 2s.
	MaxBackoff time.Duration

	// RetryIf decides whether a failed attempt is retried, replacing the
	// default policy entirely. The default retries a transport error or a
	// 429/502/503/504 response, and only for idempotent methods — a POST is
	// never retried unless RetryIf allows it. Exactly one of resp and err is
	// non-nil.
	RetryIf func(resp *Response, err error) bool
}

RetryConfig configures automatic retries, enabled via WithRetry. Zero fields fall back to the documented defaults.

Jump to

Keyboard shortcuts

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