httpclient

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 38 Imported by: ? 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 sends outgoing HTTP requests to external APIs, such as GitHub or a payment provider, and supports faking them in tests.

Call a verb helper such as Get directly, or chain configuration helpers such as Token, AcceptJSON, and EnsureSuccessful first. Requests execute through the Client belonging to the application carried in ctx, so HTTP handlers pass r while jobs, listeners, and console commands pass their ctx:

res, err := httpclient.Get(r, "https://api.github.com/users/taylorotwell")
res, err := httpclient.Token(token).AcceptJSON().EnsureSuccessful().Get(ctx, "https://api.github.com/user")

A Client is immutable: every option method returns a new client so you can configure a shared template for an API and reuse it across goroutines. Use Stream and Events for streaming downloads or server-sent events. In tests, install a Fake through httpclienttest to intercept outgoing requests without touching the network.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFaked error = notFaked{}

ErrNotFaked is returned when a Fake cannot answer a request, either because stray requests are blocked and no pattern matched or because a configured response sequence has been exhausted. Retries do not retry ErrNotFaked.

Functions

func DeleteJSON

func DeleteJSON[T any](ctx context.Context, url string) (T, error)

DeleteJSON sends an HTTP DELETE request using the application's Client from ctx, following Client.DeleteJSON. DeleteJSON panics if ctx does not carry an application scope.

func Events

func Events(body io.Reader) iter.Seq2[Event, error]

Events returns an iterator that yields each complete server-sent Event from body, such as from a Client.Stream response:

res, err := httpclient.Token(key).JSON(payload).EnsureSuccessful().Stream(ctx, http.MethodPost, "https://api.openai.com/v1/chat/completions")
if err != nil {
	return web.Fail(err)
}
defer res.Body.Close()

for event, err := range httpclient.Events(res.Body) {
	if err != nil {
		return web.Fail(err)
	}
	if event.Data == "[DONE]" {
		break
	}
	// ...
}

Events ignores SSE comments and any incomplete event at EOF. If reading body fails, Events yields the error once and stops.

func GetJSON

func GetJSON[T any](ctx context.Context, url string) (T, error)

GetJSON sends an HTTP GET request using the application's Client from ctx, following Client.GetJSON. GetJSON panics if ctx does not carry an application scope.

func PatchJSON

func PatchJSON[T any](ctx context.Context, url string) (T, error)

PatchJSON sends an HTTP PATCH request using the application's Client from ctx, following Client.PatchJSON. PatchJSON panics if ctx does not carry an application scope.

func PermanentStatus

func PermanentStatus(status int) bool

PermanentStatus reports whether status indicates a non-retryable client error, defined as any 4xx status other than 408 (Request Timeout), 409 (Conflict), and 429 (Too Many Requests).

func PostJSON

func PostJSON[T any](ctx context.Context, url string) (T, error)

PostJSON sends an HTTP POST request using the application's Client from ctx, following Client.PostJSON. PostJSON panics if ctx does not carry an application scope.

func PutJSON

func PutJSON[T any](ctx context.Context, url string) (T, error)

PutJSON sends an HTTP PUT request using the application's Client from ctx, following Client.PutJSON. PutJSON panics if ctx does not carry an application scope.

func Stream

func Stream(ctx context.Context, method, url string) (*http.Response, error)

Stream executes an HTTP request using the application's Client from ctx and returns the *http.Response as soon as headers arrive, following Client.Stream. Stream panics if ctx does not carry an application scope.

Types

type Attachment

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

Attachment represents a file uploaded in a multipart form request through Client.Attach. Create one from in-memory bytes with AttachData, from a file on disk with AttachFile, or from an incoming upload's Attachment method.

func AttachData

func AttachData(data []byte, name string) Attachment

AttachData creates an Attachment from in-memory bytes sent under the given file name.

func AttachFile

func AttachFile(path string) Attachment

AttachFile creates an Attachment backed by a file on disk, streamed as the request is sent and reopened on each retry. Relative paths are resolved against the application's base path, and the uploaded filename defaults to the base name of path.

func (Attachment) As

func (a Attachment) As(name string) Attachment

As returns a copy of a sent under a different filename. Filenames containing line breaks or other control characters cause sending the request to fail.

func (Attachment) ContentType

func (a Attachment) ContentType() string

ContentType returns the MIME type used when sending a: the value set with Attachment.WithMime, the type inferred from its filename extension, or "application/octet-stream".

func (Attachment) WithMime

func (a Attachment) WithMime(contentType string) Attachment

WithMime returns a copy of a sent with contentType instead of the MIME type inferred from its filename.

type Client

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

Client configures and sends outgoing HTTP requests. Package-level helpers such as BaseURL and Get create a client bound to the application in ctx and apply their options on top of the application's base client.

Every configuration method returns a new Client without modifying the receiver, so a configured Client is safe to share across goroutines and reuse as an API template:

github := httpclient.BaseURL("https://api.github.com").Token(token).AcceptJSON()

user, err := github.Get(ctx, "/user")
repos, err := github.Get(ctx, "/user/repos")

By default, requests wait up to 30 seconds for the full response, up to 10 seconds to establish a connection, and follow up to 10 redirects.

func Accept

func Accept(contentType string) *Client

Accept returns an application-scoped Client configured with Client.Accept.

func AcceptJSON

func AcceptJSON() *Client

AcceptJSON returns an application-scoped Client configured with Client.AcceptJSON.

func AfterResponse

func AfterResponse(hook func(res *Response)) *Client

AfterResponse returns an application-scoped Client configured with Client.AfterResponse.

func Attach

func Attach(field string, file Attachment) *Client

Attach returns an application-scoped Client configured with Client.Attach.

func BaseURL

func BaseURL(base string) *Client

BaseURL returns an application-scoped Client configured with Client.BaseURL.

func BasicAuth

func BasicAuth(username, password string) *Client

BasicAuth returns an application-scoped Client configured with Client.BasicAuth.

func BeforeSending

func BeforeSending(hook func(req *http.Request) error) *Client

BeforeSending returns an application-scoped Client configured with Client.BeforeSending.

func Body

func Body(body []byte, contentType string) *Client

Body returns an application-scoped Client configured with Client.Body.

func BodyFile

func BodyFile(path, contentType string) *Client

BodyFile returns an application-scoped Client configured with Client.BodyFile.

func CheckRedirect

func CheckRedirect(policy func(req *http.Request, via []*http.Request) error) *Client

CheckRedirect returns an application-scoped Client configured with Client.CheckRedirect.

func ConnectTimeout

func ConnectTimeout(timeout time.Duration) *Client

ConnectTimeout returns an application-scoped Client configured with Client.ConnectTimeout.

func EnsureSuccessful

func EnsureSuccessful() *Client

EnsureSuccessful returns an application-scoped Client configured with Client.EnsureSuccessful.

func Form

func Form(values url.Values) *Client

Form returns an application-scoped Client configured with Client.Form.

func Header(name, value string) *Client

Header returns an application-scoped Client configured with Client.Header.

func Headers

func Headers(headers map[string]string) *Client

Headers returns an application-scoped Client configured with Client.Headers.

func JSON

func JSON(body any) *Client

JSON returns an application-scoped Client configured with Client.JSON.

func New

func New(options Options) *Client

New creates a standalone Client with default timeouts (30 seconds overall, 10 seconds to connect) using the provided Options.

func Query

func Query(values url.Values) *Client

Query returns an application-scoped Client configured with Client.Query.

func QueryParam

func QueryParam(key, value string) *Client

QueryParam returns an application-scoped Client configured with Client.QueryParam.

func Retry

func Retry(times int, waits ...time.Duration) *Client

Retry returns an application-scoped Client configured with Client.Retry.

func RetryWhen

func RetryWhen(retry func(err error, attempt int) bool) *Client

RetryWhen returns an application-scoped Client configured with Client.RetryWhen.

func Timeout

func Timeout(timeout time.Duration) *Client

Timeout returns an application-scoped Client configured with Client.Timeout.

func Token

func Token(token string) *Client

Token returns an application-scoped Client configured with Client.Token.

func TotalTimeout

func TotalTimeout(timeout time.Duration) *Client

TotalTimeout returns an application-scoped Client configured with Client.TotalTimeout.

func Transport

func Transport(transport http.RoundTripper) *Client

Transport returns an application-scoped Client configured with Client.Transport.

func URLParameters

func URLParameters(pairs ...any) *Client

URLParameters returns an application-scoped Client configured with Client.URLParameters.

func UserAgent

func UserAgent(userAgent string) *Client

UserAgent returns an application-scoped Client configured with Client.UserAgent.

func (*Client) Accept

func (c *Client) Accept(contentType string) *Client

Accept returns a Client that sets the Accept header to contentType.

func (*Client) AcceptJSON

func (c *Client) AcceptJSON() *Client

AcceptJSON returns a Client that sets the Accept header to "application/json".

func (*Client) AfterResponse

func (c *Client) AfterResponse(hook func(res *Response)) *Client

AfterResponse returns a Client that invokes hook after every response, including retried attempts and faked responses, such as to record metrics. For Client.Stream responses, res.Body is nil unless the status code failed Client.EnsureSuccessful.

func (*Client) Attach

func (c *Client) Attach(field string, file Attachment) *Client

Attach returns a Client that attaches file under form field in a multipart request alongside any Client.Form fields. Call Attach multiple times to upload several files, reusing the same field name when sending multiple files under one field.

func (*Client) BaseURL

func (c *Client) BaseURL(base string) *Client

BaseURL returns a Client that resolves relative URLs against base. For example, with "https://api.example.com/v1", Get(ctx, "/users") requests "https://api.example.com/v1/users". Any query parameters on base are placed before those on the request URL. Absolute URLs starting with http:// or https:// are used as given.

func (*Client) BasicAuth

func (c *Client) BasicAuth(username, password string) *Client

BasicAuth returns a Client that sets the Authorization header for HTTP Basic authentication using username and password.

func (*Client) BeforeSending

func (c *Client) BeforeSending(hook func(req *http.Request) error) *Client

BeforeSending returns a Client that invokes hook on each attempt's *http.Request immediately before sending it, such as to add headers or sign the request. Hooks run in registration order; if a hook returns an error, the request fails immediately without retrying. Check req.URL to restrict a hook to a specific host:

client.BeforeSending(func(req *http.Request) error {
	if req.URL.Host == "api.example.com" {
		req.Header.Set("X-Tenant", "acme")
	}
	return nil
})

To inspect the request body without consuming it, call req.GetBody.

func (*Client) Body

func (c *Client) Body(body []byte, contentType string) *Client

Body returns a Client that sends raw bytes with the given contentType.

func (*Client) BodyFile

func (c *Client) BodyFile(path, contentType string) *Client

BodyFile returns a Client that streams the file at path as the request body directly from disk rather than buffering it in memory. Relative paths are resolved against the application's base path.

func (*Client) CheckRedirect

func (c *Client) CheckRedirect(policy func(req *http.Request, via []*http.Request) error) *Client

CheckRedirect returns a Client that uses policy to decide whether to follow redirects, matching http.Client.CheckRedirect. Return http.ErrUseLastResponse to disable redirect following.

func (*Client) ConnectTimeout

func (c *Client) ConnectTimeout(timeout time.Duration) *Client

ConnectTimeout returns a Client that uses a dedicated transport waiting up to timeout to establish TCP connections, replacing the 10-second default and any previous Client.Transport. Pass 0 for no connection timeout.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, url string) (*Response, error)

Delete sends an HTTP DELETE request to url, following Client.Send.

func (*Client) DeleteJSON

func (c *Client) DeleteJSON[T any](ctx context.Context, url string) (T, error)

DeleteJSON sends an HTTP DELETE request to url, fails with a *StatusError if the status code is not 2xx, and decodes the response body as T with Response.JSON.

func (*Client) EnsureSuccessful

func (c *Client) EnsureSuccessful() *Client

EnsureSuccessful returns a Client whose requests return a *StatusError whenever the response status code is outside the 2xx range.

func (*Client) Fake

func (c *Client) Fake(f Fake) bool

Fake installs f to intercept requests sent by c and any clients derived from c. If a fake is already installed, Fake leaves it unchanged and returns false.

func (*Client) Form

func (c *Client) Form(values url.Values) *Client

Form returns a Client that sends values as an "application/x-www-form-urlencoded" request body. When combined with Client.Attach, the fields are encoded into a multipart form alongside the attached files.

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) (*Response, error)

Get sends an HTTP GET request to url, following Client.Send.

func (*Client) GetJSON

func (c *Client) GetJSON[T any](ctx context.Context, url string) (T, error)

GetJSON sends an HTTP GET request to url, fails with a *StatusError if the status code is not 2xx, and decodes the response body as T with Response.JSON:

user, err := httpclient.Token(token).GetJSON[GitHubUser](r, "https://api.github.com/user")

func (*Client) Head

func (c *Client) Head(ctx context.Context, url string) (*Response, error)

Head sends an HTTP HEAD request to url, following Client.Send.

func (*Client) Header

func (c *Client) Header(name, value string) *Client

Header returns a Client that sets HTTP header name to value, replacing any previous value for that header. If name is not a valid HTTP token or value contains invalid control characters, sending a request fails with an error.

func (*Client) Headers

func (c *Client) Headers(headers map[string]string) *Client

Headers returns a Client that sets each header in headers, replacing any previous values for those keys. Invalid names or values fail when a request is sent.

func (*Client) JSON

func (c *Client) JSON(body any) *Client

JSON returns a Client that encodes body as JSON with Content-Type "application/json". If body cannot be marshaled to JSON, sending a request returns the encoding error.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, url string) (*Response, error)

Patch sends an HTTP PATCH request to url, following Client.Send.

func (*Client) PatchJSON

func (c *Client) PatchJSON[T any](ctx context.Context, url string) (T, error)

PatchJSON sends an HTTP PATCH request to url, fails with a *StatusError if the status code is not 2xx, and decodes the response body as T with Response.JSON.

func (*Client) Post

func (c *Client) Post(ctx context.Context, url string) (*Response, error)

Post sends an HTTP POST request to url, following Client.Send. Attach a request body first with Client.JSON, Client.Form, Client.Body, or Client.BodyFile.

func (*Client) PostJSON

func (c *Client) PostJSON[T any](ctx context.Context, url string) (T, error)

PostJSON sends an HTTP POST request to url, fails with a *StatusError if the status code is not 2xx, and decodes the response body as T with Response.JSON. Attach a request body first with Client.JSON, Client.Form, Client.Body, or Client.BodyFile.

func (*Client) Put

func (c *Client) Put(ctx context.Context, url string) (*Response, error)

Put sends an HTTP PUT request to url, following Client.Send.

func (*Client) PutJSON

func (c *Client) PutJSON[T any](ctx context.Context, url string) (T, error)

PutJSON sends an HTTP PUT request to url, fails with a *StatusError if the status code is not 2xx, and decodes the response body as T with Response.JSON.

func (*Client) Query

func (c *Client) Query(values url.Values) *Client

Query returns a Client that appends values to each request's query string after any parameters already present in the URL. Repeated calls accumulate parameters.

func (*Client) QueryParam

func (c *Client) QueryParam(key, value string) *Client

QueryParam returns a Client that appends a single query parameter to each request's query string, matching Client.Query:

res, err := httpclient.QueryParam("page", "2").QueryParam("per_page", "50").Get(r, url)

func (*Client) Retry

func (c *Client) Retry(times int, waits ...time.Duration) *Client

Retry returns a Client that makes up to times total attempts when a request fails to connect or receives a non-2xx status code, enabling Client.EnsureSuccessful automatically.

Provide one wait duration for a fixed backoff, or multiple durations to step through them in order and repeat the final duration for remaining retries:

httpclient.Retry(3, 100*time.Millisecond)
httpclient.Retry(5, 100*time.Millisecond, 200*time.Millisecond, 400*time.Millisecond, 800*time.Millisecond)

If all attempts fail, the request returns the last attempt's error. Requests are not retried when ctx is canceled, when client options are invalid, or when a fake returns ErrNotFaked.

When a 429 or 503 response includes a Retry-After header (seconds or HTTP date), Retry waits at least that long before the next attempt. If the requested delay exceeds Client.Timeout (or the configured backoff when Timeout is 0), Retry returns the *StatusError immediately instead of waiting. When Client.TotalTimeout is set, retries stop whenever the next wait would extend past the total deadline. Inspect the header on the returned error with Response.RetryAfter.

Faked requests skip sleeping between attempts, but skipped waits still count against Client.TotalTimeout so tests observe the same attempt count.

func (*Client) RetryWhen

func (c *Client) RetryWhen(retry func(err error, attempt int) bool) *Client

RetryWhen returns a Client that retries a failed attempt only when retry returns true. The attempt number starts at 1:

httpclient.Retry(3, 100*time.Millisecond).RetryWhen(func(err error, attempt int) bool {
	var failed *httpclient.ConnectionError
	return errors.As(err, &failed)
})

func (*Client) Send

func (c *Client) Send(ctx context.Context, method, url string) (*Response, error)

Send executes an HTTP request with method and url, buffering the entire response body into a *Response. Any HTTP status returns a Response and a nil error unless Client.EnsureSuccessful or Client.Retry is enabled, in which case non-2xx statuses return a *StatusError.

Send returns a *ConnectionError if no response is received after any configured retries. If c was created via a package-level helper, Send panics when ctx does not carry an application scope.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, method, url string) (*http.Response, error)

Stream executes an HTTP request and returns the *http.Response as soon as response headers arrive so you can read large downloads or Events incrementally. Always close res.Body when finished.

Retries, Client.EnsureSuccessful, and fakes behave the same as in Client.Send. When a non-2xx status fails the request, the *StatusError buffers up to 8 KiB of the response body for diagnostics. If c was created via a package-level helper, Stream panics when ctx does not carry an application scope.

func (*Client) Timeout

func (c *Client) Timeout(timeout time.Duration) *Client

Timeout returns a Client whose requests time out after waiting this long for the entire response, replacing the 30-second default. Pass 0 for no limit. For Client.Stream responses, Timeout limits the idle wait between body reads rather than the total download duration.

func (*Client) Token

func (c *Client) Token(token string) *Client

Token returns a Client that sets the Authorization header to a bearer token ("Bearer <token>").

func (*Client) TotalTimeout

func (c *Client) TotalTimeout(timeout time.Duration) *Client

TotalTimeout returns a Client that caps total elapsed time across all Client.Retry attempts and the backoff waits between them:

httpclient.Timeout(2*time.Second).Retry(5, 200*time.Millisecond).TotalTimeout(5*time.Second)

Each attempt uses the shorter of Client.Timeout and the remaining budget, and retries stop early if the next backoff wait would exceed the deadline. Pass 0 (the default) for no overall limit.

func (*Client) Transport

func (c *Client) Transport(transport http.RoundTripper) *Client

Transport returns a Client that sends requests through transport, such as an *http.Transport configured with a proxy, custom root CAs, or client certificates. Fakes installed in tests still wrap and intercept requests sent through a custom transport.

func (*Client) URLParameters

func (c *Client) URLParameters(pairs ...any) *Client

URLParameters returns a Client that substitutes {name} placeholders in the request URL using alternating name-value pairs:

res, err := httpclient.URLParameters("owner", owner, "repo", repo).Get(ctx, "https://api.github.com/repos/{owner}/{repo}")

Standard {name} placeholders percent-encode values for a single path segment and reject empty strings, ".", and ".." so values cannot traverse paths. Use {+name} to insert a pre-structured value such as a full base URL without escaping reserved characters. An odd number of arguments or a missing placeholder value causes sending the request to return an error.

func (*Client) UserAgent

func (c *Client) UserAgent(userAgent string) *Client

UserAgent returns a Client that sets the User-Agent header.

type ConnectionError

type ConnectionError struct {
	// URL is the target URL with credentials, query string, and fragment
	// redacted.
	URL string
	// Err is the underlying transport or context error.
	Err error
	// contains filtered or unexported fields
}

ConnectionError is returned when an HTTP request fails without receiving a response, such as a DNS lookup failure, unreachable host, TLS handshake error, timeout, or faked connection failure.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error formats the connection failure with the redacted URL and reason.

func (*ConnectionError) Timeout

func (e *ConnectionError) Timeout() bool

Timeout reports whether the request failed because a timeout elapsed.

func (*ConnectionError) TraceSummary

func (e *ConnectionError) TraceSummary() (string, string)

TraceSummary describes the failure by its kind: timeout, connection_refused, tls, dns, or _OTHER.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap returns the underlying transport or context error.

type DecodeError

type DecodeError struct {
	// URL is the response URL with credentials, query string, and fragment
	// redacted.
	URL string
	// Status is the HTTP status code of the response.
	Status int
	// Type is the Go type name of the decoding target.
	Type string
	// Body is a truncated preview of the response body.
	Body string
	// Err is the underlying JSON unmarshaling error.
	Err error
}

DecodeError is returned by Response.JSON when the response body cannot be decoded into the target Go value.

func (*DecodeError) Error

func (e *DecodeError) Error() string

Error formats the decode failure with the redacted URL, status, target type, body preview, and underlying error.

func (*DecodeError) TraceSummary

func (e *DecodeError) TraceSummary() (string, string)

TraceSummary describes the failure without the body that didn't decode.

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

Unwrap returns the underlying JSON decoding error.

type Event

type Event struct {
	// Name is the event type from the "event:" field, or empty if omitted.
	Name string
	// Data holds the payload assembled from one or more "data:" fields joined
	// by newlines.
	Data string
	// ID is the most recent event identifier from an "id:" field, or empty if
	// none was sent.
	ID string
}

Event represents a single server-sent event decoded by Events.

func (Event) JSON

func (e Event) JSON[T any]() (T, error)

JSON unmarshals the event's Data payload as T, returning any decoding error:

chunk, err := event.JSON[ChatChunk]()

type Fake

type Fake interface {
	// Transport returns an [http.RoundTripper] that answers faked requests and
	// delegates allowed requests to next.
	Transport(next http.RoundTripper) http.RoundTripper
}

Fake intercepts outgoing HTTP requests in tests, recording requests and returning canned responses instead of contacting the network. Install one through Client.Fake or httpclienttest.New.

type Options

type Options struct {
	// BasePath is the directory against which relative file paths for
	// [Client.BodyFile] and [AttachFile] are resolved. An empty value uses the
	// current working directory.
	BasePath string
	// Logger receives a debug log entry for each request attempt. When nil,
	// [slog.Default] is used.
	Logger *slog.Logger
	// UserAgent is the default User-Agent header sent when a request does not
	// set its own. An empty value defaults to "Laravel-Go".
	UserAgent string
}

Options configures a standalone Client created with New, such as the client created by laravel.New for an application.

type Response

type Response struct {
	// Status is the HTTP status code, such as 200.
	Status int
	// Header contains the response headers.
	Header http.Header
	// Body contains the full response body bytes.
	Body []byte
	// URL is the final URL that answered the request after any redirects.
	URL *url.URL
}

Response holds the status, headers, buffered body, and final URL of a completed HTTP request.

func Delete

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

Delete sends an HTTP DELETE request using the application's Client from ctx, following Client.Delete. Delete panics if ctx does not carry an application scope.

func Get

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

Get sends an HTTP GET request using the application's Client from ctx, following Client.Get:

res, err := httpclient.Get(r, "https://api.github.com/users/taylorotwell")

Get panics if ctx does not carry an application scope.

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

Head sends an HTTP HEAD request using the application's Client from ctx, following Client.Head. Head panics if ctx does not carry an application scope.

func Patch

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

Patch sends an HTTP PATCH request using the application's Client from ctx, following Client.Patch. Patch panics if ctx does not carry an application scope.

func Post

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

Post sends an HTTP POST request using the application's Client from ctx, following Client.Post. Chain JSON, Form, Body, or BodyFile first to attach a request body. Post panics if ctx does not carry an application scope.

func Put

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

Put sends an HTTP PUT request using the application's Client from ctx, following Client.Put. Put panics if ctx does not carry an application scope.

func Send

func Send(ctx context.Context, method, url string) (*Response, error)

Send executes an HTTP request with method and url using the application's Client from ctx, following Client.Send. Send panics if ctx does not carry an application scope.

func (*Response) ClientError

func (r *Response) ClientError() bool

ClientError reports whether the status code is in the 4xx range.

func (*Response) EnsureSuccessful

func (r *Response) EnsureSuccessful() error

EnsureSuccessful returns a *StatusError wrapping r if the status code is outside the 2xx range, or nil otherwise.

func (*Response) Failed

func (r *Response) Failed() bool

Failed reports whether the status code is in the 4xx or 5xx range.

func (*Response) JSON

func (r *Response) JSON[T any]() (T, error)

JSON unmarshals the response body as T regardless of status code. It returns a *DecodeError if the body is not valid JSON matching T:

user, err := res.JSON[GitHubUser]()

func (*Response) Redirect

func (r *Response) Redirect() bool

Redirect reports whether the status code is in the 3xx range. Because Client follows up to 10 redirects automatically, this is typically true only when redirect following is customized with Client.CheckRedirect.

func (*Response) RetryAfter

func (r *Response) RetryAfter(ctx context.Context) (time.Duration, bool)

RetryAfter parses the Retry-After header from a 429 or 503 response and returns how long the server asks clients to wait before retrying. It supports both integer seconds and HTTP-date values, measuring HTTP dates against the application clock in ctx (or the system clock outside an application) so time-travel tests observe the expected delay.

RetryAfter returns 0, false for other status codes or when the header is absent or unparseable. Queued jobs can use it to release themselves after a rate limit:

if status, ok := errors.AsType[*httpclient.StatusError](err); ok {
	if wait, ok := status.Response.RetryAfter(ctx); ok {
		return queue.Release(wait)
	}
}

func (*Response) ServerError

func (r *Response) ServerError() bool

ServerError reports whether the status code is in the 5xx range.

func (*Response) Successful

func (r *Response) Successful() bool

Successful reports whether the status code is in the 2xx range.

func (*Response) Text

func (r *Response) Text() string

Text returns the response body as a string.

type StatusError

type StatusError struct {
	Response *Response
}

StatusError is returned when a response has a non-2xx status code and Client.EnsureSuccessful or Client.Retry is enabled. Its message includes the redacted URL, status code, and the beginning of the response body.

func (*StatusError) Error

func (e *StatusError) Error() string

Error formats the status failure with the redacted URL, status, and a body preview.

func (*StatusError) Permanent

func (e *StatusError) Permanent() bool

Permanent reports whether retrying the request cannot succeed according to PermanentStatus. Queued mail, SMS, and notifications that fail with a permanent status error are not retried automatically.

func (*StatusError) TraceSummary

func (e *StatusError) TraceSummary() (string, string)

TraceSummary describes the failure by the response's status, never its body.

Jump to

Keyboard shortcuts

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