Documentation
¶
Overview ¶
Package requests provides a fluent HTTP client library for Go.
Four-object model ¶
The package is built around four public objects:
- Client owns reusable configuration: base URL, default headers and cookies, auth, retry policy, codecs, logger, and transport settings.
- RequestBuilder owns one outbound request: method, path, request-local metadata, body, timeout, retries, and middleware.
- Response exposes the buffered result of one Send call.
- StreamResponse exposes the unbuffered result of one SendStream call.
Client defaults are formed during New or Clone. State that is reused across requests belongs on Client; state for one request belongs on RequestBuilder.
Quick start ¶
client, err := requests.New(
requests.WithBaseURL("https://api.example.com"),
requests.WithTimeout(30*time.Second),
)
if err != nil {
return err
}
resp, err := client.Get("/users/{id}").
PathParam("id", "1").
Send(ctx)
if err != nil {
return err
}
defer resp.Close()
var user User
if err := resp.DecodeJSON(&user); err != nil {
return err
}
Construction ¶
Use New with functional options. Construction validates option input and returns an error instead of building a partially configured client.
Body lifecycle ¶
Request body setters fall into two groups:
- Replayable: RequestBuilder.JSON, RequestBuilder.XML, RequestBuilder.YAML, RequestBuilder.Text, RequestBuilder.Bytes, RequestBuilder.Form, RequestBuilder.FormField, and RequestBuilder.FormFields. The body is buffered or re-readable, so retries are safe.
- One-shot: RequestBuilder.Reader given a raw io.Reader that is not seekable, RequestBuilder.Files, and non-replayable RequestBuilder.Multipart. Such bodies cannot be replayed; if a retry is required, Send returns ErrRequestBodyNotReplayable instead of silently re-sending or silently skipping the retry. Use Multipart.Replayable when a multipart body must be resent.
Errors ¶
Runtime failures are returned as errors; the package does not panic and does not expose Must-style APIs. Use errors.Is with the sentinels declared in errors.go to detect specific causes, and the helpers IsTimeout, IsCanceled, and IsConnectionError to classify transport-level failures.
Extensions ¶
Optional protocol and identity behavior lives in extension modules so the core does not pull their dependencies:
- github.com/kaptinlin/requests/browser — browser-like ordered headers
- github.com/kaptinlin/requests/fingerprint — uTLS ClientHello profiles
- github.com/kaptinlin/requests/http3 — QUIC HTTP/3 transport
All three plug in through the Profile interface.
Specifications ¶
Contract-level rules live under SPECS/ in the repository. Start with SPECS/00-overview.md.
Index ¶
- Variables
- func DefaultBackoffStrategy(delay time.Duration) func(int) time.Duration
- func DefaultRetryIf(req *http.Request, resp *http.Response, err error) bool
- func ExponentialBackoffStrategy(initialInterval time.Duration, multiplier float64, ...) func(int) time.Duration
- func IsCanceled(err error) bool
- func IsConnectionError(err error) bool
- func IsTimeout(err error) bool
- func LinearBackoffStrategy(initialInterval time.Duration) func(int) time.Duration
- func OrderedHeaders(req *http.Request) (*orderedobject.Object[[]string], bool)
- func RandomProxies(proxyURLs ...string) (func(*http.Request) (*url.URL, error), error)
- func RoundRobinProxies(proxyURLs ...string) (func(*http.Request) (*url.URL, error), error)
- type AllowRedirectPolicy
- type AuthMethod
- type BackoffStrategy
- type BasicAuth
- type BearerAuth
- type Client
- func (c *Client) AsHTTPClient() *http.Client
- func (c *Client) AsTransport() http.RoundTripper
- func (c *Client) Clone(opts ...Option) (*Client, error)
- func (c *Client) Connect(path string) *RequestBuilder
- func (c *Client) Delete(path string) *RequestBuilder
- func (c *Client) Get(path string) *RequestBuilder
- func (c *Client) GetBaseURL() string
- func (c *Client) GetTLSConfig() *tls.Config
- func (c *Client) Head(path string) *RequestBuilder
- func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder
- func (c *Client) Options(path string) *RequestBuilder
- func (c *Client) Patch(path string) *RequestBuilder
- func (c *Client) Post(path string) *RequestBuilder
- func (c *Client) Put(path string) *RequestBuilder
- func (c *Client) Request(method, path string) *RequestBuilder
- func (c *Client) Trace(path string) *RequestBuilder
- func (c *Client) UnsafeHTTPClient() *http.Client
- type CustomAuth
- type Decoder
- type DefaultLogger
- type Encoder
- type File
- type FilePart
- type FormEncoder
- type JSONDecoder
- type JSONEncoder
- type Level
- type Logger
- type Middleware
- type MiddlewareHandlerFunc
- type Multipart
- func (m *Multipart) Boundary(boundary string) *Multipart
- func (m *Multipart) Field(name, value string) *Multipart
- func (m *Multipart) File(field, filename string, r io.Reader) *Multipart
- func (m *Multipart) FileBytes(field, filename string, data []byte) *Multipart
- func (m *Multipart) FileString(field, filename, data string) *Multipart
- func (m *Multipart) Part(part FilePart) *Multipart
- func (m *Multipart) Replayable(maxBytes int64) *Multipart
- type Option
- func WithAccept(accept string) Option
- func WithAuth(auth AuthMethod) Option
- func WithBaseURL(baseURL string) Option
- func WithBasicAuth(username, password string) Option
- func WithBearerAuth(token string) Option
- func WithCertificates(certs ...tls.Certificate) Option
- func WithClientCertificate(certFile, keyFile string) Option
- func WithContentType(contentType string) Option
- func WithCookieJar(jar *cookiejar.Jar) Option
- func WithCookies(cookies map[string]string) Option
- func WithDialContext(dial func(context.Context, string, string) (net.Conn, error)) Option
- func WithDialTimeout(d time.Duration) Option
- func WithHTTP2() Option
- func WithHTTPClient(httpClient *http.Client) Option
- func WithHeader(key, value string) Option
- func WithHeaders(headers *http.Header) Option
- func WithIdleConnTimeout(d time.Duration) Option
- func WithInsecureSkipVerify() Option
- func WithJSONDecoder(decoder Decoder) Option
- func WithJSONEncoder(encoder Encoder) Option
- func WithLocalAddr(addr net.Addr) Option
- func WithLogger(logger Logger) Option
- func WithMaxConnsPerHost(n int) Option
- func WithMaxIdleConns(n int) Option
- func WithMaxIdleConnsPerHost(n int) Option
- func WithMiddleware(middlewares ...Middleware) Option
- func WithOrderedHeaders(headers *orderedobject.Object[[]string]) Option
- func WithProfile(profile Profile) Option
- func WithProxies(proxyURLs ...string) Option
- func WithProxy(proxyURL string) Option
- func WithProxyBypass(proxyURL, bypass string) Option
- func WithProxyFromEnv() Option
- func WithProxySelector(selector func(*http.Request) (*url.URL, error)) Option
- func WithRedirectPolicy(policies ...RedirectPolicy) Option
- func WithReferer(referer string) Option
- func WithResolver(resolver *net.Resolver) Option
- func WithResponseHeaderTimeout(d time.Duration) Option
- func WithRetry(policy RetryPolicy) Option
- func WithRootCertificate(pemFilePath string) Option
- func WithRootCertificateFromString(pemCerts string) Option
- func WithSession() Option
- func WithTLSConfig(config *tls.Config) Option
- func WithTLSHandshakeTimeout(d time.Duration) Option
- func WithTLSServerName(serverName string) Option
- func WithTimeout(timeout time.Duration) Option
- func WithTransport(transport http.RoundTripper) Option
- func WithUserAgent(userAgent string) Option
- func WithXMLDecoder(decoder Decoder) Option
- func WithXMLEncoder(encoder Encoder) Option
- func WithYAMLDecoder(decoder Decoder) Option
- func WithYAMLEncoder(encoder Encoder) Option
- func WithoutProxy() Option
- func WithoutRetry() Option
- type Profile
- type ProhibitRedirectPolicy
- type RedirectPolicy
- type RedirectSpecifiedDomainPolicy
- type RequestBuilder
- func (b *RequestBuilder) Accept(accept string) *RequestBuilder
- func (b *RequestBuilder) AddHeader(key, value string) *RequestBuilder
- func (b *RequestBuilder) AddMiddleware(middlewares ...Middleware)
- func (b *RequestBuilder) Auth(auth AuthMethod) *RequestBuilder
- func (b *RequestBuilder) Bytes(v []byte) *RequestBuilder
- func (b *RequestBuilder) Clone() *RequestBuilder
- func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder
- func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder
- func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder
- func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder
- func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder
- func (b *RequestBuilder) Files(files ...*File) *RequestBuilder
- func (b *RequestBuilder) Form(v any) *RequestBuilder
- func (b *RequestBuilder) FormField(key, val string) *RequestBuilder
- func (b *RequestBuilder) FormFields(fields any) *RequestBuilder
- func (b *RequestBuilder) Header(key, value string) *RequestBuilder
- func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder
- func (b *RequestBuilder) JSON(v any) *RequestBuilder
- func (b *RequestBuilder) Method(method string) *RequestBuilder
- func (b *RequestBuilder) Multipart(m *Multipart) *RequestBuilder
- func (b *RequestBuilder) NoRetry() *RequestBuilder
- func (b *RequestBuilder) OrderedHeaders(headers *orderedobject.Object[[]string]) *RequestBuilder
- func (b *RequestBuilder) Path(path string) *RequestBuilder
- func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder
- func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder
- func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder
- func (b *RequestBuilder) QueriesStruct(queryStruct any) *RequestBuilder
- func (b *RequestBuilder) Query(key, value string) *RequestBuilder
- func (b *RequestBuilder) Reader(r io.Reader, contentType string) *RequestBuilder
- func (b *RequestBuilder) Referer(referer string) *RequestBuilder
- func (b *RequestBuilder) Retry(policy RetryPolicy) *RequestBuilder
- func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)
- func (b *RequestBuilder) SendStream(ctx context.Context) (*StreamResponse, error)
- func (b *RequestBuilder) Text(v string) *RequestBuilder
- func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
- func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder
- func (b *RequestBuilder) XML(v any) *RequestBuilder
- func (b *RequestBuilder) YAML(v any) *RequestBuilder
- type Response
- func (r *Response) Attempts() int
- func (r *Response) Bytes() []byte
- func (r *Response) Close() error
- func (r *Response) ContentLength() int
- func (r *Response) ContentType() string
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Decode(v any) error
- func (r *Response) DecodeJSON(v any) error
- func (r *Response) DecodeXML(v any) error
- func (r *Response) DecodeYAML(v any) error
- func (r *Response) Elapsed() time.Duration
- func (r *Response) Header() http.Header
- func (r *Response) IsClientError() bool
- func (r *Response) IsContentType(contentType string) bool
- func (r *Response) IsEmpty() bool
- func (r *Response) IsError() bool
- func (r *Response) IsJSON() bool
- func (r *Response) IsRedirect() bool
- func (r *Response) IsServerError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) IsXML() bool
- func (r *Response) IsYAML() bool
- func (r *Response) Lines() iter.Seq[[]byte]
- func (r *Response) Location() (*url.URL, error)
- func (r *Response) Protocol() string
- func (r *Response) Raw() *http.Response
- func (r *Response) Save(v any) error
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() string
- func (r *Response) TLS() *tls.ConnectionState
- func (r *Response) URL() *url.URL
- type RetryIfFunc
- type RetryPolicy
- type SmartRedirectPolicy
- type StreamResponse
- func (r *StreamResponse) Attempts() int
- func (r *StreamResponse) Body() io.ReadCloser
- func (r *StreamResponse) Close() error
- func (r *StreamResponse) Elapsed() time.Duration
- func (r *StreamResponse) Header() http.Header
- func (r *StreamResponse) Lines() iter.Seq2[[]byte, error]
- func (r *StreamResponse) Raw() *http.Response
- func (r *StreamResponse) Status() string
- func (r *StreamResponse) StatusCode() int
- func (r *StreamResponse) URL() *url.URL
- type XMLDecoder
- type XMLEncoder
- type YAMLDecoder
- type YAMLEncoder
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnsupportedContentType is returned when a body encoder cannot handle // the request's Content-Type, or when a raw body is given a value type // other than string, []byte, or io.Reader. Set Content-Type explicitly or // use a typed body setter (JSON, XML, YAML, Text, Bytes). ErrUnsupportedContentType = errors.New("unsupported content type") // ErrUnsupportedDataType is returned when a decoder cannot handle the // destination type. Pass a pointer to a struct, map, or slice that the // codec can populate. ErrUnsupportedDataType = errors.New("unsupported data type") // ErrEncodingFailed is returned when an encoder rejects a body value. // Wrapped errors carry the codec-specific cause; inspect with errors.As. ErrEncodingFailed = errors.New("encoding failed") // ErrRequestCreationFailed is returned when http.NewRequestWithContext // rejects the resolved method, URL, or body. Almost always indicates a // malformed BaseURL + path combination; verify with errors.As to surface // the underlying *url.Error. ErrRequestCreationFailed = errors.New("failed to create request") // ErrRequestBodyNotReplayable is returned when retries are configured but // the body is a one-shot io.Reader from [RequestBuilder.Reader]. Switch // to a buffered body setter such as JSON, Bytes, Form, or call // Multipart.Replayable(maxBytes) to opt in to buffering for multipart. ErrRequestBodyNotReplayable = errors.New("request body is not replayable") // ErrRequestBodyReadIncomplete is returned when a sized request body // (ReadAt+Seek+Size) reports fewer bytes than its declared size. Indicates // a truncated source; do not retry until the source is fixed. ErrRequestBodyReadIncomplete = errors.New("request body read incomplete") // ErrResponseReadFailed is returned when the response body cannot be read // in full. Wrapped errors carry the I/O cause. ErrResponseReadFailed = errors.New("failed to read response") // ErrUnsupportedScheme is returned when a proxy URL uses a scheme other // than http, https, or socks5. ErrUnsupportedScheme = errors.New("unsupported proxy scheme") // ErrNoProxies is returned when a proxy rotation function is given an // empty list of proxy URLs. ErrNoProxies = errors.New("no proxy URLs provided") // ErrUnsupportedFormFieldsType is returned when [RequestBuilder.FormFields] // or [RequestBuilder.Form] receives a value that is not a struct, map, or // url.Values. ErrUnsupportedFormFieldsType = errors.New("unsupported form fields type") // ErrNotSupportSaveMethod is returned when [Response.Save] is given a // destination it does not understand. Use a string path, *os.File, or // io.Writer. ErrNotSupportSaveMethod = errors.New("unsupported save type") // ErrInvalidTransportType is returned when a TLS or HTTP/2 helper is // asked to mutate a transport that is not *http.Transport. Set the // transport before applying TLS/HTTP/2 options, or apply the option to a // *http.Transport directly. ErrInvalidTransportType = errors.New("invalid transport type") // ErrResponseNil is returned when transport returned no error and no // response. Indicates a transport bug; the request should not be retried // blindly. ErrResponseNil = errors.New("response is nil") // ErrAutoRedirectDisabled is returned by [ProhibitRedirectPolicy] when a // 3xx response would normally trigger a follow-up request. ErrAutoRedirectDisabled = errors.New("auto redirect disabled") // ErrTooManyRedirects is returned when a redirect chain exceeds the // configured limit. Wrapped errors include the observed limit. ErrTooManyRedirects = errors.New("too many redirects") // ErrRedirectNotAllowed is returned by [RedirectSpecifiedDomainPolicy] // when the redirect target host is not in the allow-list. ErrRedirectNotAllowed = errors.New("redirect not allowed") // ErrTestTimeout is reserved for use by the package's own tests. It is // not produced by Send. ErrTestTimeout = errors.New("test timeout: request took too long") // ErrInvalidConfigValue is returned by construction options when a value // cannot be applied. Wrapped errors name the offending option. ErrInvalidConfigValue = errors.New("invalid config value") )
Sentinel errors returned by the package. Use errors.Is to match against them. The classification helpers below (IsTimeout, IsCanceled, IsConnectionError) cover the most common transport-level questions without forcing callers to enumerate every cause.
var DefaultFormEncoder = &FormEncoder{}
DefaultFormEncoder is the default FormEncoder instance.
var DefaultJSONDecoder = &JSONDecoder{}
DefaultJSONDecoder is the default JSONDecoder instance using the JSON v2 streaming decoder.
var DefaultJSONEncoder = &JSONEncoder{
MarshalFunc: jsonMarshal,
}
DefaultJSONEncoder is the default JSONEncoder instance using the JSON v2 marshal function.
var DefaultXMLDecoder = &XMLDecoder{ UnmarshalFunc: xml.Unmarshal, }
DefaultXMLDecoder is the default XMLDecoder instance using the standard xml.Unmarshal function.
var DefaultXMLEncoder = &XMLEncoder{ MarshalFunc: xml.Marshal, }
DefaultXMLEncoder is the default XMLEncoder instance using the standard xml.Marshal function.
var DefaultYAMLDecoder = &YAMLDecoder{}
DefaultYAMLDecoder is the default YAMLDecoder instance using the goccy/go-yaml streaming decoder.
var DefaultYAMLEncoder = &YAMLEncoder{ MarshalFunc: yaml.Marshal, }
DefaultYAMLEncoder is the default YAMLEncoder instance using the goccy/go-yaml Marshal function.
Functions ¶
func DefaultBackoffStrategy ¶
DefaultBackoffStrategy provides a simple constant delay between retries.
func DefaultRetryIf ¶
DefaultRetryIf is a simple retry condition that retries on transport errors, request timeouts, rate limiting, and 5xx status codes.
func ExponentialBackoffStrategy ¶
func ExponentialBackoffStrategy(initialInterval time.Duration, multiplier float64, maxBackoffTime time.Duration) func(int) time.Duration
ExponentialBackoffStrategy increases the delay exponentially with each retry attempt.
func IsCanceled ¶ added in v0.6.0
IsCanceled reports whether err is or wraps context.Canceled, which indicates the caller cancelled the request before completion. Use this to distinguish caller-initiated cancellation from deadline-driven timeout (see IsTimeout).
func IsConnectionError ¶ added in v0.3.13
IsConnectionError reports whether err is a connection-level failure (DNS resolution, TCP connect, TLS handshake), as surfaced by net.OpError.
func IsTimeout ¶ added in v0.3.13
IsTimeout reports whether err is or wraps a deadline-driven failure: context.DeadlineExceeded from a request or per-call timeout, or any net.Error whose Timeout method returns true (for example, dial, TLS-handshake, or response-header timeouts).
IsTimeout intentionally does not match context.Canceled; use IsCanceled for explicit cancellation.
func LinearBackoffStrategy ¶
LinearBackoffStrategy increases the delay linearly with each retry attempt. The delay increments by `initialInterval` with each attempt.
func OrderedHeaders ¶ added in v0.5.0
OrderedHeaders returns the ordered header metadata attached to req, when present.
Default net/http transports do not guarantee wire-order delivery. This metadata is intended for transports that explicitly support ordered headers.
func RandomProxies ¶ added in v0.3.13
RandomProxies returns a proxy function that selects a random proxy for each request. Safe for concurrent use.
Types ¶
type AllowRedirectPolicy ¶ added in v0.2.3
type AllowRedirectPolicy struct {
// contains filtered or unexported fields
}
AllowRedirectPolicy is a redirect policy that allows a flexible number of redirects.
func NewAllowRedirectPolicy ¶ added in v0.2.3
func NewAllowRedirectPolicy(numberRedirects int) *AllowRedirectPolicy
NewAllowRedirectPolicy creates a new AllowRedirectPolicy that allows up to the specified number of redirects.
type AuthMethod ¶
type AuthMethod interface {
// Apply applies the authentication strategy to req.
Apply(req *http.Request)
// Valid reports whether the authentication strategy is configured.
Valid() bool
}
AuthMethod defines the interface for applying authentication strategies to requests.
type BackoffStrategy ¶
BackoffStrategy defines a function that returns the delay before the next retry.
func JitterBackoffStrategy ¶ added in v0.3.13
func JitterBackoffStrategy(base BackoffStrategy, fraction float64) BackoffStrategy
JitterBackoffStrategy wraps a base backoff strategy and applies random jitter. The fraction parameter controls the jitter range: the delay is adjusted by plus or minus the fraction of the base delay. For example, a fraction of 0.25 means plus or minus 25% jitter.
type BasicAuth ¶
type BasicAuth struct {
Username string // Username is the HTTP Basic Authentication username.
Password string // Password is the HTTP Basic Authentication password.
}
BasicAuth represents HTTP Basic Authentication credentials.
type BearerAuth ¶
type BearerAuth struct {
Token string // Token is the bearer token value.
}
BearerAuth represents an OAuth 2.0 Bearer token.
func (BearerAuth) Apply ¶
func (b BearerAuth) Apply(req *http.Request)
Apply adds the Bearer token to the request's Authorization header.
func (BearerAuth) Valid ¶
func (b BearerAuth) Valid() bool
Valid checks if the Bearer token is present.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents an HTTP client.
func New ¶ added in v0.3.14
New creates a Client with functional options applied. It returns an error when any option cannot be applied.
func (*Client) AsHTTPClient ¶ added in v0.5.0
AsHTTPClient returns a net/http client that applies this client's defaults.
The returned client preserves the underlying timeout, cookie jar, redirect policy, and transport at the time AsHTTPClient is called. Its transport applies client headers, cookies, auth, and client-level middleware. RequestBuilder-only behavior such as retries, response buffering, streaming callbacks, and decoding helpers is not part of the returned client.
func (*Client) AsTransport ¶ added in v0.5.0
func (c *Client) AsTransport() http.RoundTripper
AsTransport returns a RoundTripper that applies this client's defaults.
Use it when another library owns the *http.Client and only lets callers replace http.Client.Transport. The returned transport snapshots client headers, cookies, auth, middleware, and the underlying transport at call time.
func (*Client) Clone ¶ added in v0.6.5
Clone returns a new Client with the current defaults plus opts applied.
func (*Client) Connect ¶ added in v0.3.12
func (c *Client) Connect(path string) *RequestBuilder
Connect initiates a CONNECT request.
func (*Client) Delete ¶
func (c *Client) Delete(path string) *RequestBuilder
Delete initiates a DELETE request.
func (*Client) Get ¶
func (c *Client) Get(path string) *RequestBuilder
Get initiates a GET request.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/kaptinlin/requests"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprint(w, `{"id":1,"title":"delectus aut autem"}`)
}))
defer server.Close()
type post struct {
ID int `json:"id"`
Title string `json:"title"`
}
client, err := requests.New(
requests.WithBaseURL(server.URL),
requests.WithTimeout(5*time.Second),
)
if err != nil {
fmt.Println("client error:", err)
return
}
resp, err := client.Get("/posts/{id}").PathParam("id", "1").Send(context.Background())
if err != nil {
fmt.Println("request error:", err)
return
}
defer func() { _ = resp.Close() }()
var p post
if err := resp.DecodeJSON(&p); err != nil {
fmt.Println("decode error:", err)
return
}
fmt.Println(p.ID, p.Title)
}
Output: 1 delectus aut autem
func (*Client) GetBaseURL ¶ added in v0.4.0
GetBaseURL returns the configured base URL in a thread-safe way.
func (*Client) GetTLSConfig ¶ added in v0.6.5
GetTLSConfig returns a clone of the configured TLS settings.
func (*Client) Head ¶
func (c *Client) Head(path string) *RequestBuilder
Head initiates a HEAD request.
func (*Client) NewRequestBuilder ¶
func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder
NewRequestBuilder creates a new RequestBuilder with default settings.
func (*Client) Options ¶
func (c *Client) Options(path string) *RequestBuilder
Options initiates an OPTIONS request.
func (*Client) Patch ¶
func (c *Client) Patch(path string) *RequestBuilder
Patch initiates a PATCH request.
func (*Client) Post ¶
func (c *Client) Post(path string) *RequestBuilder
Post initiates a POST request.
func (*Client) Request ¶ added in v0.6.5
func (c *Client) Request(method, path string) *RequestBuilder
Request initiates a request with method and path.
func (*Client) Trace ¶ added in v0.3.12
func (c *Client) Trace(path string) *RequestBuilder
Trace initiates a TRACE request.
func (*Client) UnsafeHTTPClient ¶ added in v0.6.5
UnsafeHTTPClient returns the underlying HTTP client for advanced integration.
The returned pointer is shared mutable client state. Callers that mutate it must coordinate their own synchronization and should prefer construction options when possible.
type CustomAuth ¶
type CustomAuth struct {
Header string // Header is the Authorization header value.
}
CustomAuth allows for custom Authorization header values.
func (CustomAuth) Apply ¶
func (c CustomAuth) Apply(req *http.Request)
Apply sets a custom Authorization header value.
func (CustomAuth) Valid ¶
func (c CustomAuth) Valid() bool
Valid checks if the custom Authorization header value is present.
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger is a default logger that uses `slog` as the underlying logger.
func (*DefaultLogger) Debugf ¶ added in v0.1.1
func (l *DefaultLogger) Debugf(format string, v ...any)
Debugf logs a message at the Debug level.
func (*DefaultLogger) Errorf ¶ added in v0.1.1
func (l *DefaultLogger) Errorf(format string, v ...any)
Errorf logs a message at the Error level.
func (*DefaultLogger) Infof ¶ added in v0.1.1
func (l *DefaultLogger) Infof(format string, v ...any)
Infof logs a message at the Info level.
func (*DefaultLogger) SetLevel ¶ added in v0.1.1
func (l *DefaultLogger) SetLevel(level Level)
SetLevel sets the log level of the logger.
func (*DefaultLogger) Warnf ¶ added in v0.1.1
func (l *DefaultLogger) Warnf(format string, v ...any)
Warnf logs a message at the Warn level.
type Encoder ¶
type Encoder interface {
// Encode encodes v and returns a reader for the encoded payload.
Encode(v any) (io.Reader, error)
// ContentType returns the payload content type.
ContentType() string
}
Encoder encodes values into an io.Reader with an associated content type.
type File ¶
type File struct {
Name string // Name is the form field name.
FileName string // FileName is the uploaded file name.
Content io.ReadCloser // Content is the uploaded file content.
}
File represents a form file.
func (*File) SetContent ¶
func (f *File) SetContent(content io.ReadCloser)
SetContent sets the content of the file.
func (*File) SetFileName ¶
SetFileName sets the file name.
type JSONDecoder ¶
type JSONDecoder struct {
DecodeFunc func(r io.Reader, v any) error // DecodeFunc decodes JSON data into a value.
}
JSONDecoder handles decoding of JSON data.
type JSONEncoder ¶
type JSONEncoder struct {
MarshalFunc func(v any) ([]byte, error) // MarshalFunc marshals a value into JSON.
}
JSONEncoder handles encoding of JSON data.
func (*JSONEncoder) ContentType ¶
func (e *JSONEncoder) ContentType() string
ContentType returns the content type for JSON data.
type Logger ¶
type Logger interface {
// Debugf logs a message at the Debug level.
Debugf(format string, v ...any)
// Infof logs a message at the Info level.
Infof(format string, v ...any)
// Warnf logs a message at the Warn level.
Warnf(format string, v ...any)
// Errorf logs a message at the Error level.
Errorf(format string, v ...any)
// SetLevel sets the log level of the logger.
SetLevel(level Level)
}
Logger is a logger interface that outputs logs with a format.
type Middleware ¶
type Middleware func(next MiddlewareHandlerFunc) MiddlewareHandlerFunc
Middleware wraps a MiddlewareHandlerFunc with additional behavior.
type MiddlewareHandlerFunc ¶
MiddlewareHandlerFunc handles an HTTP request and returns an HTTP response.
type Multipart ¶ added in v0.5.0
type Multipart struct {
// contains filtered or unexported fields
}
Multipart builds a multipart/form-data request body.
func NewMultipart ¶ added in v0.5.0
func NewMultipart() *Multipart
NewMultipart creates an empty multipart builder.
func (*Multipart) FileString ¶ added in v0.5.0
FileString adds a file part backed by a string.
func (*Multipart) Replayable ¶ added in v0.5.0
Replayable buffers the multipart body up to maxBytes so it can be replayed for retries.
type Option ¶ added in v0.6.5
Option configures a Client during construction.
func WithAccept ¶ added in v0.3.14
WithAccept sets the default Accept header.
func WithAuth ¶ added in v0.3.14
func WithAuth(auth AuthMethod) Option
WithAuth sets the authentication method for the client.
func WithBaseURL ¶ added in v0.3.14
WithBaseURL sets the base URL for the client.
func WithBasicAuth ¶ added in v0.3.14
WithBasicAuth sets HTTP Basic Authentication credentials.
func WithBearerAuth ¶ added in v0.3.14
WithBearerAuth sets a Bearer token for authentication.
func WithCertificates ¶ added in v0.3.14
func WithCertificates(certs ...tls.Certificate) Option
WithCertificates sets TLS client certificates.
func WithClientCertificate ¶ added in v0.4.0
WithClientCertificate loads and sets a client certificate and key from file paths.
func WithContentType ¶ added in v0.3.14
WithContentType sets the default Content-Type header.
func WithCookieJar ¶ added in v0.3.14
WithCookieJar sets the cookie jar for the client.
func WithCookies ¶ added in v0.3.14
WithCookies sets default cookies on the client.
func WithDialContext ¶ added in v0.5.0
WithDialContext sets the dial function on the underlying transport.
func WithDialTimeout ¶ added in v0.3.14
WithDialTimeout sets the TCP connection timeout on the underlying transport.
func WithHTTP2 ¶ added in v0.5.0
func WithHTTP2() Option
WithHTTP2 enables HTTP/2 transport support.
func WithHTTPClient ¶ added in v0.3.14
WithHTTPClient sets the underlying http.Client. When combined with transport-modifying options (WithProxy, WithDialTimeout, etc.), place WithHTTPClient first since it replaces the entire http.Client.
func WithHeader ¶ added in v0.3.14
WithHeader sets a default header on the client.
func WithHeaders ¶ added in v0.3.14
WithHeaders sets all default headers on the client.
func WithIdleConnTimeout ¶ added in v0.3.14
WithIdleConnTimeout sets how long idle connections remain in the pool.
func WithInsecureSkipVerify ¶ added in v0.3.14
func WithInsecureSkipVerify() Option
WithInsecureSkipVerify configures the client to skip TLS certificate verification.
func WithJSONDecoder ¶ added in v0.6.5
WithJSONDecoder sets the JSON decoder.
func WithJSONEncoder ¶ added in v0.6.5
WithJSONEncoder sets the JSON encoder.
func WithLocalAddr ¶ added in v0.5.0
WithLocalAddr sets the local address used by the default transport dialer.
func WithLogger ¶ added in v0.3.14
WithLogger sets the logger for the client.
func WithMaxConnsPerHost ¶ added in v0.3.14
WithMaxConnsPerHost sets the maximum total number of connections per host.
func WithMaxIdleConns ¶ added in v0.3.14
WithMaxIdleConns sets the maximum number of idle connections across all hosts.
func WithMaxIdleConnsPerHost ¶ added in v0.3.14
WithMaxIdleConnsPerHost sets the maximum number of idle connections per host.
func WithMiddleware ¶ added in v0.3.14
func WithMiddleware(middlewares ...Middleware) Option
WithMiddleware adds middleware to the client.
func WithOrderedHeaders ¶ added in v0.5.0
func WithOrderedHeaders(headers *orderedobject.Object[[]string]) Option
WithOrderedHeaders sets ordered default headers on the client.
func WithProfile ¶ added in v0.5.0
WithProfile applies a coherent client identity profile.
func WithProxies ¶ added in v0.6.5
WithProxies sets multiple proxies with round-robin rotation.
func WithProxyBypass ¶ added in v0.6.5
WithProxyBypass sets a proxy URL with a NO_PROXY-style bypass list.
func WithProxyFromEnv ¶ added in v0.6.5
func WithProxyFromEnv() Option
WithProxyFromEnv uses proxy settings from HTTP_PROXY, HTTPS_PROXY, and NO_PROXY.
func WithProxySelector ¶ added in v0.6.5
WithProxySelector sets a custom proxy selection function.
func WithRedirectPolicy ¶ added in v0.3.14
func WithRedirectPolicy(policies ...RedirectPolicy) Option
WithRedirectPolicy sets the redirect policy for the client.
func WithReferer ¶ added in v0.3.14
WithReferer sets the default Referer header.
func WithResolver ¶ added in v0.5.0
WithResolver sets the resolver used by the default transport dialer.
func WithResponseHeaderTimeout ¶ added in v0.3.14
WithResponseHeaderTimeout sets the time to wait for response headers.
func WithRetry ¶ added in v0.6.5
func WithRetry(policy RetryPolicy) Option
WithRetry sets the default retry policy.
func WithRootCertificate ¶ added in v0.3.14
WithRootCertificate sets the root certificate from a PEM file path.
func WithRootCertificateFromString ¶ added in v0.3.14
WithRootCertificateFromString sets the root certificate from a PEM string.
func WithSession ¶ added in v0.5.0
func WithSession() Option
WithSession enables cookie and TLS session reuse.
func WithTLSConfig ¶ added in v0.3.14
WithTLSConfig sets the TLS configuration for the client.
func WithTLSHandshakeTimeout ¶ added in v0.3.14
WithTLSHandshakeTimeout sets the TLS handshake timeout on the underlying transport.
func WithTLSServerName ¶ added in v0.4.0
WithTLSServerName sets the TLS server name (SNI).
func WithTimeout ¶ added in v0.3.14
WithTimeout sets the default timeout for the client.
func WithTransport ¶ added in v0.3.14
func WithTransport(transport http.RoundTripper) Option
WithTransport sets the HTTP transport for the client.
func WithUserAgent ¶ added in v0.3.14
WithUserAgent sets the default User-Agent header.
func WithXMLDecoder ¶ added in v0.6.5
WithXMLDecoder sets the XML decoder.
func WithXMLEncoder ¶ added in v0.6.5
WithXMLEncoder sets the XML encoder.
func WithYAMLDecoder ¶ added in v0.6.5
WithYAMLDecoder sets the YAML decoder.
func WithYAMLEncoder ¶ added in v0.6.5
WithYAMLEncoder sets the YAML encoder.
func WithoutProxy ¶ added in v0.6.5
func WithoutProxy() Option
WithoutProxy clears any configured proxy.
func WithoutRetry ¶ added in v0.6.5
func WithoutRetry() Option
WithoutRetry disables retry attempts.
type Profile ¶ added in v0.5.0
Profile contributes coherent client identity options during construction.
type ProhibitRedirectPolicy ¶ added in v0.2.3
type ProhibitRedirectPolicy struct {
}
ProhibitRedirectPolicy is a redirect policy that does not allow any redirects.
func NewProhibitRedirectPolicy ¶ added in v0.2.3
func NewProhibitRedirectPolicy() *ProhibitRedirectPolicy
NewProhibitRedirectPolicy creates a new ProhibitRedirectPolicy that prevents any redirects.
type RedirectPolicy ¶ added in v0.2.3
type RedirectPolicy interface {
// Apply applies the redirect policy to req based on the prior requests in via.
Apply(req *http.Request, via []*http.Request) error
}
RedirectPolicy applies redirect behavior to outgoing requests.
type RedirectSpecifiedDomainPolicy ¶ added in v0.2.3
type RedirectSpecifiedDomainPolicy struct {
// contains filtered or unexported fields
}
RedirectSpecifiedDomainPolicy is a redirect policy that checks if the redirect is allowed based on the hostnames.
func NewRedirectSpecifiedDomainPolicy ¶ added in v0.2.3
func NewRedirectSpecifiedDomainPolicy(domains ...string) *RedirectSpecifiedDomainPolicy
NewRedirectSpecifiedDomainPolicy creates a new RedirectSpecifiedDomainPolicy that only allows redirects to the specified domains.
type RequestBuilder ¶
type RequestBuilder struct {
// contains filtered or unexported fields
}
RequestBuilder facilitates building and executing HTTP requests.
func (*RequestBuilder) Accept ¶
func (b *RequestBuilder) Accept(accept string) *RequestBuilder
Accept sets the Accept header for the request.
func (*RequestBuilder) AddHeader ¶
func (b *RequestBuilder) AddHeader(key, value string) *RequestBuilder
AddHeader adds a header to the request.
func (*RequestBuilder) AddMiddleware ¶
func (b *RequestBuilder) AddMiddleware(middlewares ...Middleware)
AddMiddleware adds a middleware to the request.
func (*RequestBuilder) Auth ¶
func (b *RequestBuilder) Auth(auth AuthMethod) *RequestBuilder
Auth applies an authentication method to the request.
func (*RequestBuilder) Bytes ¶ added in v0.6.5
func (b *RequestBuilder) Bytes(v []byte) *RequestBuilder
Bytes sets the request body as raw bytes without changing Content-Type. The body is buffered and is safe to replay for retries.
func (*RequestBuilder) Clone ¶ added in v0.3.13
func (b *RequestBuilder) Clone() *RequestBuilder
Clone creates a deep copy of the RequestBuilder. The clone shares the same client reference (shallow copy) but has independent copies of headers, cookies, queries, pathParams, and formFields (deep copy). This means configuration changes to the client will affect both the original and clone.
Body data, multipart bodies, form files, middlewares, and retry config are not copied as they are not safe to share or clone. Set these on the cloned builder if needed.
func (*RequestBuilder) ContentType ¶
func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder
ContentType sets the Content-Type header for the request.
func (*RequestBuilder) Cookie ¶
func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder
Cookie adds a cookie to the request.
func (*RequestBuilder) Cookies ¶
func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder
Cookies adds cookies from a map.
func (*RequestBuilder) DelCookie ¶
func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder
DelCookie removes one or more cookies from the request.
func (*RequestBuilder) DelFile ¶
func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder
DelFile removes one or more files from the request.
func (*RequestBuilder) DelFormField ¶
func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder
DelFormField removes one or more form fields.
func (*RequestBuilder) DelHeader ¶
func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder
DelHeader removes one or more headers from the request.
func (*RequestBuilder) DelPathParam ¶
func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder
DelPathParam removes one or more path params fields from the RequestBuilder instance.
func (*RequestBuilder) DelQuery ¶
func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder
DelQuery removes one or more query parameters from the request.
func (*RequestBuilder) File ¶
func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder
File adds a file to the request. The resulting multipart body is streamed once; use Multipart.Replayable with RequestBuilder.Multipart when retries must resend the body.
func (*RequestBuilder) Files ¶
func (b *RequestBuilder) Files(files ...*File) *RequestBuilder
Files sets multiple files at once. The resulting multipart body is streamed once; use Multipart.Replayable with RequestBuilder.Multipart when retries must resend the body.
func (*RequestBuilder) Form ¶
func (b *RequestBuilder) Form(v any) *RequestBuilder
Form sets form fields and files for the request from a struct, map, or url.Values. The resulting body is buffered and is safe to replay for retries.
func (*RequestBuilder) FormField ¶
func (b *RequestBuilder) FormField(key, val string) *RequestBuilder
FormField adds or updates a form field. Without files, the resulting form body is buffered and safe to replay for retries.
func (*RequestBuilder) FormFields ¶
func (b *RequestBuilder) FormFields(fields any) *RequestBuilder
FormFields sets multiple form fields at once. The resulting body is buffered and is safe to replay for retries.
func (*RequestBuilder) Header ¶
func (b *RequestBuilder) Header(key, value string) *RequestBuilder
Header sets (or replaces) a header in the request.
func (*RequestBuilder) Headers ¶
func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder
Headers set headers to the request.
func (*RequestBuilder) JSON ¶ added in v0.6.5
func (b *RequestBuilder) JSON(v any) *RequestBuilder
JSON sets the request body as JSON and Content-Type to application/json. The encoded body is buffered and is safe to replay for retries.
func (*RequestBuilder) Method ¶
func (b *RequestBuilder) Method(method string) *RequestBuilder
Method sets the HTTP method for the request.
func (*RequestBuilder) Multipart ¶ added in v0.5.0
func (b *RequestBuilder) Multipart(m *Multipart) *RequestBuilder
Multipart sets a multipart/form-data body built by Multipart.
By default the body is streamed once via an io.Pipe and is not replayable; a retry that needs to resend the body returns ErrRequestBodyNotReplayable. Call m.Replayable(maxBytes) before passing the builder if retries must resend the body.
func (*RequestBuilder) NoRetry ¶ added in v0.6.5
func (b *RequestBuilder) NoRetry() *RequestBuilder
NoRetry disables retries for this request.
func (*RequestBuilder) OrderedHeaders ¶ added in v0.5.0
func (b *RequestBuilder) OrderedHeaders(headers *orderedobject.Object[[]string]) *RequestBuilder
OrderedHeaders sets ordered headers for the request.
func (*RequestBuilder) Path ¶
func (b *RequestBuilder) Path(path string) *RequestBuilder
Path sets the URL path for the request.
func (*RequestBuilder) PathParam ¶
func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder
PathParam sets a single path param field and its value in the RequestBuilder instance.
func (*RequestBuilder) PathParams ¶
func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder
PathParams sets multiple path params fields and their values at one go in the RequestBuilder instance.
func (*RequestBuilder) Queries ¶
func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder
Queries adds query parameters to the request.
func (*RequestBuilder) QueriesStruct ¶
func (b *RequestBuilder) QueriesStruct(queryStruct any) *RequestBuilder
QueriesStruct adds query parameters to the request based on a struct tagged with url tags.
func (*RequestBuilder) Query ¶
func (b *RequestBuilder) Query(key, value string) *RequestBuilder
Query adds a single query parameter to the request.
func (*RequestBuilder) Reader ¶ added in v0.6.5
func (b *RequestBuilder) Reader(r io.Reader, contentType string) *RequestBuilder
Reader sets a one-shot raw request body and optional Content-Type. The body is not replayable unless r itself is seekable and sized.
func (*RequestBuilder) Referer ¶
func (b *RequestBuilder) Referer(referer string) *RequestBuilder
Referer sets the Referer header for the request.
func (*RequestBuilder) Retry ¶ added in v0.6.5
func (b *RequestBuilder) Retry(policy RetryPolicy) *RequestBuilder
Retry sets the request-local retry policy, replacing the client policy.
func (*RequestBuilder) Send ¶
func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)
Send executes the HTTP request.
Send takes a snapshot of the client at call time; later mutations on the client do not affect this in-flight request.
Cancellation: ctx propagates through dial, TLS handshake, request header read, body read, retry backoff, and stream callbacks. When ctx is canceled before the response arrives, Send returns ctx.Err() and any partial response is closed internally. When ctx is canceled after the response is returned, the caller is still responsible for calling Response.Close to release the underlying connection.
Retries: if the request body cannot be replayed, retries that would need to resend the body return ErrRequestBodyNotReplayable instead of silently re-sending or silently skipping.
func (*RequestBuilder) SendStream ¶ added in v0.6.5
func (b *RequestBuilder) SendStream(ctx context.Context) (*StreamResponse, error)
SendStream sends the request and returns an unbuffered streaming response.
func (*RequestBuilder) Text ¶ added in v0.6.5
func (b *RequestBuilder) Text(v string) *RequestBuilder
Text sets the request body as plain text and Content-Type to text/plain. The body is buffered and is safe to replay for retries.
func (*RequestBuilder) Timeout ¶
func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
Timeout sets the request timeout.
func (*RequestBuilder) UserAgent ¶
func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder
UserAgent sets the User-Agent header for the request.
func (*RequestBuilder) XML ¶ added in v0.6.5
func (b *RequestBuilder) XML(v any) *RequestBuilder
XML sets the request body as XML and Content-Type to application/xml. The encoded body is buffered and is safe to replay for retries.
func (*RequestBuilder) YAML ¶ added in v0.6.5
func (b *RequestBuilder) YAML(v any) *RequestBuilder
YAML sets the request body as YAML and Content-Type to application/yaml. The encoded body is buffered and is safe to replay for retries.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response represents an HTTP response.
func (*Response) Attempts ¶ added in v0.5.0
Attempts returns the total number of transport attempts, including the first request.
func (*Response) Bytes ¶ added in v0.6.5
Bytes returns the response body as a caller-owned byte slice.
func (*Response) ContentLength ¶
ContentLength returns the length of the response body.
func (*Response) ContentType ¶
ContentType returns the value of the "Content-Type" header.
func (*Response) Decode ¶ added in v0.6.5
Decode decodes the response body based on its content type.
func (*Response) DecodeJSON ¶ added in v0.6.5
DecodeJSON decodes the response body as JSON.
func (*Response) DecodeYAML ¶ added in v0.6.5
DecodeYAML decodes the response body as YAML.
func (*Response) Elapsed ¶ added in v0.5.0
Elapsed returns the duration from request dispatch through response setup.
func (*Response) IsClientError ¶ added in v0.3.13
IsClientError checks if the response status code indicates a client error (400 - 499).
func (*Response) IsContentType ¶
IsContentType checks if the response Content-Type header matches a given content type.
func (*Response) IsError ¶ added in v0.3.13
IsError checks if the response status code indicates an error (>= 400).
func (*Response) IsRedirect ¶ added in v0.3.13
IsRedirect checks if the response status code indicates a redirect (300 - 399).
func (*Response) IsServerError ¶ added in v0.3.13
IsServerError checks if the response status code indicates a server error (>= 500).
func (*Response) IsSuccess ¶
IsSuccess checks if the response status code indicates success (200 - 299).
func (*Response) Lines ¶ added in v0.2.4
Lines returns an iterator over the buffered response body lines.
func (*Response) Protocol ¶ added in v0.5.0
Protocol returns the response protocol, such as "HTTP/1.1" or "HTTP/2.0".
func (*Response) Raw ¶ added in v0.6.5
Raw returns the underlying HTTP response for callers that need net/http details.
func (*Response) StatusCode ¶
StatusCode returns the HTTP status code of the response.
func (*Response) TLS ¶ added in v0.5.0
func (r *Response) TLS() *tls.ConnectionState
TLS returns a copy of the response TLS connection state, if any.
type RetryIfFunc ¶
RetryIfFunc defines the function signature for retry conditions.
type RetryPolicy ¶ added in v0.6.5
type RetryPolicy struct {
// Max is the number of retry attempts after the first delivery attempt.
Max int
// Backoff returns the delay before the next retry.
Backoff BackoffStrategy
// ShouldRetry decides whether an HTTP response should be retried.
ShouldRetry RetryIfFunc
// IgnoreRetryAfter makes Backoff authoritative even when Retry-After is present.
IgnoreRetryAfter bool
}
RetryPolicy describes retry delivery as one value.
func DefaultRetryPolicy ¶ added in v0.6.5
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy returns the default retry behavior with retries disabled.
type SmartRedirectPolicy ¶ added in v0.3.13
type SmartRedirectPolicy struct {
// contains filtered or unexported fields
}
SmartRedirectPolicy is a redirect policy that downgrades POST to GET on 301/302/303 redirects and strips sensitive headers on cross-host or scheme-downgrade redirects.
func NewSmartRedirectPolicy ¶ added in v0.3.13
func NewSmartRedirectPolicy(maxRedirects int) *SmartRedirectPolicy
NewSmartRedirectPolicy creates a new SmartRedirectPolicy with the given redirect limit.
type StreamResponse ¶ added in v0.6.5
type StreamResponse struct {
// contains filtered or unexported fields
}
StreamResponse is an unbuffered HTTP response whose body is owned by the caller.
func (*StreamResponse) Attempts ¶ added in v0.6.5
func (r *StreamResponse) Attempts() int
Attempts returns the total number of transport attempts, including the first request.
func (*StreamResponse) Body ¶ added in v0.6.5
func (r *StreamResponse) Body() io.ReadCloser
Body returns the live response body. The caller must close the response.
func (*StreamResponse) Close ¶ added in v0.6.5
func (r *StreamResponse) Close() error
Close closes the response body and releases the request context.
func (*StreamResponse) Elapsed ¶ added in v0.6.5
func (r *StreamResponse) Elapsed() time.Duration
Elapsed returns the duration from request dispatch through response setup.
func (*StreamResponse) Header ¶ added in v0.6.5
func (r *StreamResponse) Header() http.Header
Header returns the response headers.
func (*StreamResponse) Lines ¶ added in v0.6.5
func (r *StreamResponse) Lines() iter.Seq2[[]byte, error]
Lines returns an iterator over streamed response body lines.
func (*StreamResponse) Raw ¶ added in v0.6.5
func (r *StreamResponse) Raw() *http.Response
Raw returns the underlying HTTP response for callers that need net/http details.
func (*StreamResponse) Status ¶ added in v0.6.5
func (r *StreamResponse) Status() string
Status returns the status string of the response.
func (*StreamResponse) StatusCode ¶ added in v0.6.5
func (r *StreamResponse) StatusCode() int
StatusCode returns the HTTP status code of the response.
func (*StreamResponse) URL ¶ added in v0.6.5
func (r *StreamResponse) URL() *url.URL
URL returns the request URL that elicited the response.
type XMLDecoder ¶
type XMLDecoder struct {
UnmarshalFunc func(data []byte, v any) error // UnmarshalFunc unmarshals XML data into a value.
}
XMLDecoder handles decoding of XML data.
type XMLEncoder ¶
type XMLEncoder struct {
MarshalFunc func(v any) ([]byte, error) // MarshalFunc marshals a value into XML.
}
XMLEncoder handles encoding of XML data.
func (*XMLEncoder) ContentType ¶
func (e *XMLEncoder) ContentType() string
ContentType returns the content type for XML data.
type YAMLDecoder ¶
type YAMLDecoder struct {
DecodeFunc func(r io.Reader, v any) error // DecodeFunc decodes YAML data into a value.
}
YAMLDecoder handles decoding of YAML data.
type YAMLEncoder ¶
type YAMLEncoder struct {
MarshalFunc func(v any) ([]byte, error) // MarshalFunc marshals a value into YAML.
}
YAMLEncoder handles encoding of YAML data.
func (*YAMLEncoder) ContentType ¶
func (e *YAMLEncoder) ContentType() string
ContentType returns the content type for YAML data.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
browser
module
|
|
|
The examples command demonstrates basic usage of the requests package.
|
The examples command demonstrates basic usage of the requests package. |
|
fingerprint
module
|
|
|
http3
module
|
|
|
Package middlewares provides reusable middleware components for the requests HTTP client, including caching, cookie management, and header injection.
|
Package middlewares provides reusable middleware components for the requests HTTP client, including caching, cookie management, and header injection. |