Documentation
¶
Overview ¶
Package httpx provides a simple HTTP client.
Index ¶
- Constants
- func DefaultTransport() *http.Transport
- func DrainResponseBody(resp *http.Response) error
- func IsSuccess(resp *http.Response) bool
- func ReadJSON(resp *http.Response, val any) error
- func WriteJSON(val any) (*bytes.Buffer, error)
- type Client
- func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error)
- func (c *Client) Get(ctx context.Context, uri string) (resp *http.Response, err error)
- func (c *Client) Head(ctx context.Context, uri string) (resp *http.Response, err error)
- func (c *Client) Post(ctx context.Context, uri, contentType string, body io.Reader) (resp *http.Response, err error)
- func (c *Client) PostForm(ctx context.Context, uri string, data url.Values) (resp *http.Response, err error)
- type Error
- type Logger
- type RateLimitExceededError
- type RetryAfterExceededError
- type RetryPolicy
- type UserAgent
Examples ¶
Constants ¶
const ( // ErrCannotDecodeJSON is returned when a JSON response cannot be decoded. ErrCannotDecodeJSON xerrors.Error = "cannot decode JSON response" // ErrCannotEncodeJSON is returned when a JSON request cannot be encoded. ErrCannotEncodeJSON xerrors.Error = "cannot encode JSON request" // ErrCannotDrainResponse is returned when a response body cannot be drained. ErrCannotDrainResponse xerrors.Error = "cannot drain response body" // ErrCannotCloseResponse is returned when a response body cannot be closed. ErrCannotCloseResponse xerrors.Error = "cannot close response body" // ErrNilVal is returned when a nil value is passed to a function. ErrNilValue xerrors.Error = "val cannot be nil" )
const DefaultTimeout = 10 * time.Second
DefaultTimeout is the default timeout for all requests made by the client.
const ErrRetryCanceled xerrors.Error = "retry canceled"
ErrRetryCanceled is returned when the request is canceled while waiting to retry.
Variables ¶
This section is empty.
Functions ¶
func DefaultTransport ¶
DefaultTransport returns a *http.Transport with optimized security and performance settings for common use cases.
func DrainResponseBody ¶
DrainResponseBody drains the response body until EOF and closes it. It returns an error if the drain or close fails.
DrainResponseBody reads and discards the remaining content of the response body until EOF, then closes it. If an error occurs while draining or closing the response body, an error is returned.
Types ¶
type Client ¶
type Client struct { // RateLimiter specifies a client-side requests per second limit. // // Ultimately, most APIs enforce this limit on their side, but this is a // good way to be a good citizen. RateLimiter *rate.Limiter // RetryPolicy specifies the policy for retrying requests. RetryPolicy *RetryPolicy // UserAgent is the User-Agent header to use for all requests. UserAgent *UserAgent // Transport specifies the mechanism by which individual HTTP requests are // made. If nil, DefaultTransport is used. Transport http.RoundTripper // CheckRedirect specifies the policy for handling redirects. If // CheckRedirect is nil, the Client uses its default policy, which is to // not follow redirects at all. CheckRedirect func(req *http.Request, via []*http.Request) error // Jar specifies the cookie jar. If nil, cookies are only sent if they are // explicitly set on the Request. Jar http.CookieJar // Cache is an optional cache mechanism to store HTTP responses. Cache pagecache.Cache // Logger is the logger to use for logging requests when debugging. Logger Logger // Timeout is the timeout for all requests made by the client, overriding // the default value set in the underlying http.Client. Timeout time.Duration // Debug specifies whether or not to enable debug logging. Debug bool // contains filtered or unexported fields }
func NewClientWithCache ¶
func NewClientWithCache(cache pagecache.Cache) *Client
NewClientWithCache returns a new Client with default settings and a storage mechanism for caching HTTP responses.
If cache is nil, a default in-memory cache will be used.
func (*Client) Get ¶
Get is a convenience method for making GET requests.
Example ¶
client := httpx.NewClientWithCache(nil) resp, err := client.Get(context.Background(), "https://example.com/") if err != nil { log.Fatal(err) } defer resp.Body.Close() fmt.Println(resp.StatusCode)
Output: 200
type Error ¶
type Error struct { // URL is the URL that was requested. URL *url.URL // Method is the HTTP method used. Method string // Message is a human-readable error message. Message string // StatusText is the HTTP status text. StatusText string // StatusCode is the HTTP status code. StatusCode int }
Error is a generic HTTP error type that can be used to return more information about a request failure.
type Logger ¶
Logger defines the interface for logging. It is basically a thin wrapper around the standard logger which implements only a subset of the logger API.
func DefaultLogger ¶
func DefaultLogger() Logger
DefaultLogger is the default logger used by HTTPX when Client.Debug is true.
type RateLimitExceededError ¶
type RateLimitExceededError struct { // ResetTime is the time at which the rate limit will reset. ResetTime time.Time // Remaining is the number of requests remaining in the current time window. Remaining int // Limit is the maximum number of requests allowed within a specific time // window. Limit int }
RateLimitExceededError represents an error that occurs when the rate limit for an HTTP request has been exceeded.
func (*RateLimitExceededError) Error ¶
func (e *RateLimitExceededError) Error() string
Error returns a human-readable error message describing the rate limit exceeded error. It implements the error interface.
type RetryAfterExceededError ¶
type RetryAfterExceededError struct { // RetryAfter is the duration specified in the Retry-After header, indicating // the time clients should wait before sending another request. RetryAfter time.Duration // MaxRetries is the maximum number of retries allowed for an HTTP request. MaxRetries int }
RetryAfterExceededError represents an error that occurs when the maximum number of retries for an HTTP request has been exceeded.
func (*RetryAfterExceededError) Error ¶
func (e *RetryAfterExceededError) Error() string
Error returns a human-readable error message describing the retry limit exceeded error. It implements the error interface.
type RetryPolicy ¶
type RetryPolicy struct { // RetryableStatusCodes is a slice of HTTP status codes that should trigger // a retry. // // If a response's status code is in this slice, the request will be // retried according to the policy. RetryableStatusCodes []int // MaxRetries is the maximum number of times a request will be retried if // it encounters a retryable status code. MaxRetries int // MinRetryDelay is the minimum duration to wait before retrying a request. MinRetryDelay time.Duration // MaxRetryDelay is the maximum duration to wait before retrying a request. MaxRetryDelay time.Duration // contains filtered or unexported fields }
RetryPolicy defines a policy for retrying HTTP requests.
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() *RetryPolicy
DefaultRetryPolicy returns a RetryPolicy with sensible defaults for retrying HTTP requests.
func (*RetryPolicy) RetryAfter ¶
func (p *RetryPolicy) RetryAfter(resp *http.Response) time.Duration
RetryAfter returns the amount of time to wait before retrying a request based on the "Retry-After" header.
If the header is not present, the returned duration is MinRetryDelay with added jitter to prevent thundering herds.
func (*RetryPolicy) ShouldRetry ¶
func (p *RetryPolicy) ShouldRetry(resp *http.Response) bool
ShouldRetry checks if the response's status code indicates that the request should be retried.
type UserAgent ¶
type UserAgent struct { // Token is the product token. Token string // Version is the product version. Version string // Comment is the product comment. Comment []string }
UserAgent represents the User-Agent header value, as defined in RFC 7231, section 5.5.3.
func DefaultUserAgent ¶
func DefaultUserAgent() *UserAgent
DefaultUserAgent returns the default User-Agent header value for the httpx package.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
internal
|
|
build
Package build provides build information about [the httpx package].
|
Package build provides build information about [the httpx package]. |
separator
Package separator provide constant string separators for several use cases.
|
Package separator provide constant string separators for several use cases. |