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 ¶
- Variables
- func DeleteJSON[T any](ctx context.Context, url string) (T, error)
- func Events(body io.Reader) iter.Seq2[Event, error]
- func GetJSON[T any](ctx context.Context, url string) (T, error)
- func PatchJSON[T any](ctx context.Context, url string) (T, error)
- func PermanentStatus(status int) bool
- func PostJSON[T any](ctx context.Context, url string) (T, error)
- func PutJSON[T any](ctx context.Context, url string) (T, error)
- func Stream(ctx context.Context, method, url string) (*http.Response, error)
- type Attachment
- type Client
- func Accept(contentType string) *Client
- func AcceptJSON() *Client
- func AfterResponse(hook func(res *Response)) *Client
- func Attach(field string, file Attachment) *Client
- func BaseURL(base string) *Client
- func BasicAuth(username, password string) *Client
- func BeforeSending(hook func(req *http.Request) error) *Client
- func Body(body []byte, contentType string) *Client
- func BodyFile(path, contentType string) *Client
- func CheckRedirect(policy func(req *http.Request, via []*http.Request) error) *Client
- func ConnectTimeout(timeout time.Duration) *Client
- func EnsureSuccessful() *Client
- func Form(values url.Values) *Client
- func Header(name, value string) *Client
- func Headers(headers map[string]string) *Client
- func JSON(body any) *Client
- func New(options Options) *Client
- func Query(values url.Values) *Client
- func QueryParam(key, value string) *Client
- func Retry(times int, waits ...time.Duration) *Client
- func RetryWhen(retry func(err error, attempt int) bool) *Client
- func Timeout(timeout time.Duration) *Client
- func Token(token string) *Client
- func TotalTimeout(timeout time.Duration) *Client
- func Transport(transport http.RoundTripper) *Client
- func URLParameters(pairs ...any) *Client
- func UserAgent(userAgent string) *Client
- func (c *Client) Accept(contentType string) *Client
- func (c *Client) AcceptJSON() *Client
- func (c *Client) AfterResponse(hook func(res *Response)) *Client
- func (c *Client) Attach(field string, file Attachment) *Client
- func (c *Client) BaseURL(base string) *Client
- func (c *Client) BasicAuth(username, password string) *Client
- func (c *Client) BeforeSending(hook func(req *http.Request) error) *Client
- func (c *Client) Body(body []byte, contentType string) *Client
- func (c *Client) BodyFile(path, contentType string) *Client
- func (c *Client) CheckRedirect(policy func(req *http.Request, via []*http.Request) error) *Client
- func (c *Client) ConnectTimeout(timeout time.Duration) *Client
- func (c *Client) Delete(ctx context.Context, url string) (*Response, error)
- func (c *Client) DeleteJSON[T any](ctx context.Context, url string) (T, error)
- func (c *Client) EnsureSuccessful() *Client
- func (c *Client) Fake(f Fake) bool
- func (c *Client) Form(values url.Values) *Client
- func (c *Client) Get(ctx context.Context, url string) (*Response, error)
- func (c *Client) GetJSON[T any](ctx context.Context, url string) (T, error)
- func (c *Client) Head(ctx context.Context, url string) (*Response, error)
- func (c *Client) Header(name, value string) *Client
- func (c *Client) Headers(headers map[string]string) *Client
- func (c *Client) JSON(body any) *Client
- func (c *Client) Patch(ctx context.Context, url string) (*Response, error)
- func (c *Client) PatchJSON[T any](ctx context.Context, url string) (T, error)
- func (c *Client) Post(ctx context.Context, url string) (*Response, error)
- func (c *Client) PostJSON[T any](ctx context.Context, url string) (T, error)
- func (c *Client) Put(ctx context.Context, url string) (*Response, error)
- func (c *Client) PutJSON[T any](ctx context.Context, url string) (T, error)
- func (c *Client) Query(values url.Values) *Client
- func (c *Client) QueryParam(key, value string) *Client
- func (c *Client) Retry(times int, waits ...time.Duration) *Client
- func (c *Client) RetryWhen(retry func(err error, attempt int) bool) *Client
- func (c *Client) Send(ctx context.Context, method, url string) (*Response, error)
- func (c *Client) Stream(ctx context.Context, method, url string) (*http.Response, error)
- func (c *Client) Timeout(timeout time.Duration) *Client
- func (c *Client) Token(token string) *Client
- func (c *Client) TotalTimeout(timeout time.Duration) *Client
- func (c *Client) Transport(transport http.RoundTripper) *Client
- func (c *Client) URLParameters(pairs ...any) *Client
- func (c *Client) UserAgent(userAgent string) *Client
- type ConnectionError
- type DecodeError
- type Event
- type Fake
- type Options
- type Response
- func Delete(ctx context.Context, url string) (*Response, error)
- func Get(ctx context.Context, url string) (*Response, error)
- func Head(ctx context.Context, url string) (*Response, error)
- func Patch(ctx context.Context, url string) (*Response, error)
- func Post(ctx context.Context, url string) (*Response, error)
- func Put(ctx context.Context, url string) (*Response, error)
- func Send(ctx context.Context, method, url string) (*Response, error)
- func (r *Response) ClientError() bool
- func (r *Response) EnsureSuccessful() error
- func (r *Response) Failed() bool
- func (r *Response) JSON[T any]() (T, error)
- func (r *Response) Redirect() bool
- func (r *Response) RetryAfter(ctx context.Context) (time.Duration, bool)
- func (r *Response) ServerError() bool
- func (r *Response) Successful() bool
- func (r *Response) Text() string
- type StatusError
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
BaseURL returns an application-scoped Client configured with Client.BaseURL.
func BasicAuth ¶
BasicAuth returns an application-scoped Client configured with Client.BasicAuth.
func BeforeSending ¶
BeforeSending returns an application-scoped Client configured with Client.BeforeSending.
func Body ¶
Body returns an application-scoped Client configured with Client.Body.
func BodyFile ¶
BodyFile returns an application-scoped Client configured with Client.BodyFile.
func CheckRedirect ¶
CheckRedirect returns an application-scoped Client configured with Client.CheckRedirect.
func ConnectTimeout ¶
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 ¶
Form returns an application-scoped Client configured with Client.Form.
func Header ¶
Header returns an application-scoped Client configured with Client.Header.
func Headers ¶
Headers returns an application-scoped Client configured with Client.Headers.
func JSON ¶
JSON returns an application-scoped Client configured with Client.JSON.
func New ¶
New creates a standalone Client with default timeouts (30 seconds overall, 10 seconds to connect) using the provided Options.
func Query ¶
Query returns an application-scoped Client configured with Client.Query.
func QueryParam ¶
QueryParam returns an application-scoped Client configured with Client.QueryParam.
func Retry ¶
Retry returns an application-scoped Client configured with Client.Retry.
func RetryWhen ¶
RetryWhen returns an application-scoped Client configured with Client.RetryWhen.
func Timeout ¶
Timeout returns an application-scoped Client configured with Client.Timeout.
func Token ¶
Token returns an application-scoped Client configured with Client.Token.
func TotalTimeout ¶
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 ¶
URLParameters returns an application-scoped Client configured with Client.URLParameters.
func UserAgent ¶
UserAgent returns an application-scoped Client configured with Client.UserAgent.
func (*Client) AcceptJSON ¶
AcceptJSON returns a Client that sets the Accept header to "application/json".
func (*Client) AfterResponse ¶
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 ¶
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 ¶
BasicAuth returns a Client that sets the Authorization header for HTTP Basic authentication using username and password.
func (*Client) BeforeSending ¶
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) BodyFile ¶
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 ¶
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 ¶
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 ¶
Delete sends an HTTP DELETE request to url, following Client.Send.
func (*Client) DeleteJSON ¶
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 ¶
EnsureSuccessful returns a Client whose requests return a *StatusError whenever the response status code is outside the 2xx range.
func (*Client) Fake ¶
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 ¶
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 ¶
Get sends an HTTP GET request to url, following Client.Send.
func (*Client) GetJSON ¶
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 ¶
Head sends an HTTP HEAD request to url, following Client.Send.
func (*Client) Header ¶
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 ¶
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 ¶
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 ¶
Patch sends an HTTP PATCH request to url, following Client.Send.
func (*Client) PatchJSON ¶
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 ¶
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 ¶
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 ¶
Put sends an HTTP PUT request to url, following Client.Send.
func (*Client) PutJSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Token returns a Client that sets the Authorization header to a bearer token ("Bearer <token>").
func (*Client) TotalTimeout ¶
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 ¶
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ClientError reports whether the status code is in the 4xx range.
func (*Response) EnsureSuccessful ¶
EnsureSuccessful returns a *StatusError wrapping r if the status code is outside the 2xx range, or nil otherwise.
func (*Response) JSON ¶
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 ¶
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 ¶
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 ¶
ServerError reports whether the status code is in the 5xx range.
func (*Response) Successful ¶
Successful reports whether the status code is in the 2xx range.
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.