Documentation
¶
Overview ¶
Package requests provides a fluent HTTP client library for Go.
Runtime failures are returned as errors rather than panics, and the package does not expose Must-style APIs.
Index ¶
- Constants
- 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 GetBuffer() *bytebufferpool.ByteBuffer
- 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 PutBuffer(b *bytebufferpool.ByteBuffer)
- 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) AddDefaultHeader(key, value string)
- func (c *Client) AddMiddleware(middlewares ...Middleware)
- func (c *Client) ApplyProfile(profile Profile) error
- func (c *Client) AsHTTPClient() *http.Client
- func (c *Client) AsTransport() http.RoundTripper
- func (c *Client) Connect(path string) *RequestBuilder
- func (c *Client) Custom(path, method string) *RequestBuilder
- func (c *Client) DelDefaultCookie(name string)
- func (c *Client) DelDefaultHeader(key string)
- func (c *Client) Delete(path string) *RequestBuilder
- func (c *Client) EnableHTTP2() *Client
- func (c *Client) EnableSession() *Client
- func (c *Client) Get(path string) *RequestBuilder
- func (c *Client) GetBaseURL() string
- func (c *Client) GetHTTPClient() *http.Client
- func (c *Client) Head(path string) *RequestBuilder
- func (c *Client) InsecureSkipVerify() *Client
- 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) RemoveProxy()
- func (c *Client) SetAuth(auth AuthMethod)
- func (c *Client) SetBaseURL(baseURL string)
- func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
- func (c *Client) SetClientCertificate(certFile, keyFile string) *Client
- func (c *Client) SetClientRootCertificate(pemFilePath string) *Client
- func (c *Client) SetClientRootCertificateFromString(pemCerts string) *Client
- func (c *Client) SetDefaultAccept(accept string)
- func (c *Client) SetDefaultContentType(contentType string)
- func (c *Client) SetDefaultCookie(name, value string)
- func (c *Client) SetDefaultCookieJar(jar *cookiejar.Jar)
- func (c *Client) SetDefaultCookies(cookies map[string]string)
- func (c *Client) SetDefaultHeader(key, value string)
- func (c *Client) SetDefaultHeaders(headers *http.Header)
- func (c *Client) SetDefaultOrderedHeaders(headers *orderedobject.Object[[]string])
- func (c *Client) SetDefaultReferer(referer string)
- func (c *Client) SetDefaultTimeout(timeout time.Duration)
- func (c *Client) SetDefaultTransport(transport http.RoundTripper)
- func (c *Client) SetDefaultUserAgent(userAgent string)
- func (c *Client) SetDialContext(dial func(context.Context, string, string) (net.Conn, error)) *Client
- func (c *Client) SetDialTimeout(d time.Duration) *Client
- func (c *Client) SetHTTPClient(httpClient *http.Client)
- func (c *Client) SetIdleConnTimeout(d time.Duration) *Client
- func (c *Client) SetJSONMarshal(marshalFunc func(v any) ([]byte, error))
- func (c *Client) SetJSONUnmarshal(unmarshalFunc func(data []byte, v any) error)
- func (c *Client) SetLocalAddr(addr net.Addr) *Client
- func (c *Client) SetLogger(logger Logger) *Client
- func (c *Client) SetMaxConnsPerHost(n int) *Client
- func (c *Client) SetMaxIdleConns(n int) *Client
- func (c *Client) SetMaxIdleConnsPerHost(n int) *Client
- func (c *Client) SetMaxRetries(maxRetries int) *Client
- func (c *Client) SetProxies(proxyURLs ...string) error
- func (c *Client) SetProxy(proxyURL string) error
- func (c *Client) SetProxyFromEnv() error
- func (c *Client) SetProxySelector(selector func(*http.Request) (*url.URL, error)) error
- func (c *Client) SetProxyWithBypass(proxyURL, bypass string) error
- func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client
- func (c *Client) SetResolver(resolver *net.Resolver) *Client
- func (c *Client) SetResponseHeaderTimeout(d time.Duration) *Client
- func (c *Client) SetRetryIf(retryIf RetryIfFunc) *Client
- func (c *Client) SetRetryStrategy(strategy BackoffStrategy) *Client
- func (c *Client) SetRootCertificate(pemFilePath string) *Client
- func (c *Client) SetRootCertificateFromString(pemCerts string) *Client
- func (c *Client) SetTLSConfig(config *tls.Config) *Client
- func (c *Client) SetTLSHandshakeTimeout(d time.Duration) *Client
- func (c *Client) SetTLSServerName(serverName string) *Client
- func (c *Client) SetXMLMarshal(marshalFunc func(v any) ([]byte, error))
- func (c *Client) SetXMLUnmarshal(unmarshalFunc func(data []byte, v any) error)
- func (c *Client) SetYAMLMarshal(marshalFunc func(v any) ([]byte, error))
- func (c *Client) SetYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error)
- func (c *Client) Trace(path string) *RequestBuilder
- type ClientOption
- func WithAccept(accept string) ClientOption
- func WithAuth(auth AuthMethod) ClientOption
- func WithBaseURL(baseURL string) ClientOption
- func WithBasicAuth(username, password string) ClientOption
- func WithBearerAuth(token string) ClientOption
- func WithCertificates(certs ...tls.Certificate) ClientOption
- func WithClientCertificate(certFile, keyFile string) ClientOption
- func WithContentType(contentType string) ClientOption
- func WithCookieJar(jar *cookiejar.Jar) ClientOption
- func WithCookies(cookies map[string]string) ClientOption
- func WithDialContext(dial func(context.Context, string, string) (net.Conn, error)) ClientOption
- func WithDialTimeout(d time.Duration) ClientOption
- func WithHTTP2() ClientOption
- func WithHTTPClient(httpClient *http.Client) ClientOption
- func WithHeader(key, value string) ClientOption
- func WithHeaders(headers *http.Header) ClientOption
- func WithIdleConnTimeout(d time.Duration) ClientOption
- func WithInsecureSkipVerify() ClientOption
- func WithJSONMarshal(marshalFunc func(v any) ([]byte, error)) ClientOption
- func WithJSONUnmarshal(unmarshalFunc func(data []byte, v any) error) ClientOption
- func WithLocalAddr(addr net.Addr) ClientOption
- func WithLogger(logger Logger) ClientOption
- func WithMaxConnsPerHost(n int) ClientOption
- func WithMaxIdleConns(n int) ClientOption
- func WithMaxIdleConnsPerHost(n int) ClientOption
- func WithMaxRetries(maxRetries int) ClientOption
- func WithMiddleware(middlewares ...Middleware) ClientOption
- func WithOrderedHeaders(headers *orderedobject.Object[[]string]) ClientOption
- func WithProfile(profile Profile) ClientOption
- func WithProxy(proxyURL string) ClientOption
- func WithRedirectPolicy(policies ...RedirectPolicy) ClientOption
- func WithReferer(referer string) ClientOption
- func WithResolver(resolver *net.Resolver) ClientOption
- func WithResponseHeaderTimeout(d time.Duration) ClientOption
- func WithRetryIf(retryIf RetryIfFunc) ClientOption
- func WithRetryStrategy(strategy BackoffStrategy) ClientOption
- func WithRootCertificate(pemFilePath string) ClientOption
- func WithRootCertificateFromString(pemCerts string) ClientOption
- func WithSession() ClientOption
- func WithTLSConfig(config *tls.Config) ClientOption
- func WithTLSHandshakeTimeout(d time.Duration) ClientOption
- func WithTLSServerName(serverName string) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- func WithTransport(transport http.RoundTripper) ClientOption
- func WithUserAgent(userAgent string) ClientOption
- func WithXMLMarshal(marshalFunc func(v any) ([]byte, error)) ClientOption
- func WithXMLUnmarshal(unmarshalFunc func(data []byte, v any) error) ClientOption
- func WithYAMLMarshal(marshalFunc func(v any) ([]byte, error)) ClientOption
- func WithYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error) ClientOption
- type Config
- 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 NoProxy
- 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) Body(body any) *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) JSONBody(v any) *RequestBuilder
- func (b *RequestBuilder) MaxRetries(maxRetries int) *RequestBuilder
- func (b *RequestBuilder) Method(method string) *RequestBuilder
- func (b *RequestBuilder) Multipart(m *Multipart) *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) RawBody(v []byte) *RequestBuilder
- func (b *RequestBuilder) Referer(referer string) *RequestBuilder
- func (b *RequestBuilder) RetryIf(retryIf RetryIfFunc) *RequestBuilder
- func (b *RequestBuilder) RetryStrategy(strategy BackoffStrategy) *RequestBuilder
- func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)
- func (b *RequestBuilder) Stream(callback StreamCallback) *RequestBuilder
- func (b *RequestBuilder) StreamDone(callback StreamDoneCallback) *RequestBuilder
- func (b *RequestBuilder) StreamErr(callback StreamErrCallback) *RequestBuilder
- func (b *RequestBuilder) TextBody(v string) *RequestBuilder
- func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
- func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder
- func (b *RequestBuilder) XMLBody(v any) *RequestBuilder
- func (b *RequestBuilder) YAMLBody(v any) *RequestBuilder
- type Response
- func (r *Response) Attempts() int
- func (r *Response) Body() []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) 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) Save(v any) error
- func (r *Response) Scan(v any) error
- func (r *Response) ScanJSON(v any) error
- func (r *Response) ScanXML(v any) error
- func (r *Response) ScanYAML(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 RetryConfig
- type RetryIfFunc
- type SmartRedirectPolicy
- type StreamCallback
- type StreamDoneCallback
- type StreamErrCallback
- type XMLDecoder
- type XMLEncoder
- type YAMLDecoder
- type YAMLEncoder
Examples ¶
Constants ¶
const DirPermissions = 0o750
DirPermissions is the permission mode used when Save creates parent directories.
const MaxStreamBufferSize = 512 * 1024
MaxStreamBufferSize is the maximum size of the buffer used for streaming.
Variables ¶
var ( // ErrUnsupportedContentType is returned when the content type is unsupported. ErrUnsupportedContentType = errors.New("unsupported content type") // ErrUnsupportedDataType is returned when the data type is unsupported. ErrUnsupportedDataType = errors.New("unsupported data type") // ErrEncodingFailed is returned when the encoding fails. ErrEncodingFailed = errors.New("encoding failed") // ErrRequestCreationFailed is returned when the request cannot be created. ErrRequestCreationFailed = errors.New("failed to create request") // ErrRequestBodyNotReplayable is returned when a retry needs a request body that cannot be replayed. ErrRequestBodyNotReplayable = errors.New("request body is not replayable") // ErrRequestBodyReadIncomplete is returned when a replayable request body cannot be fully read. ErrRequestBodyReadIncomplete = errors.New("request body read incomplete") // ErrResponseReadFailed is returned when the response cannot be read. ErrResponseReadFailed = errors.New("failed to read response") // ErrUnsupportedScheme is returned when the proxy scheme is unsupported. ErrUnsupportedScheme = errors.New("unsupported proxy scheme") // ErrNoProxies is returned when no proxy URLs are provided to a rotation function. ErrNoProxies = errors.New("no proxy URLs provided") // ErrUnsupportedFormFieldsType is returned when the form fields type is unsupported. ErrUnsupportedFormFieldsType = errors.New("unsupported form fields type") // ErrNotSupportSaveMethod is returned when the provided type for saving is not supported. ErrNotSupportSaveMethod = errors.New("unsupported save type") // ErrInvalidTransportType is returned when the transport type is invalid. ErrInvalidTransportType = errors.New("invalid transport type") // ErrResponseNil is returned when the response is nil. ErrResponseNil = errors.New("response is nil") // ErrAutoRedirectDisabled is returned when the auto redirect is disabled. ErrAutoRedirectDisabled = errors.New("auto redirect disabled") // ErrTooManyRedirects is returned when the number of redirects is too many. ErrTooManyRedirects = errors.New("too many redirects") // ErrRedirectNotAllowed is returned when the redirect is not allowed. ErrRedirectNotAllowed = errors.New("redirect not allowed") // ErrTestTimeout is returned when a test request times out (used in tests). ErrTestTimeout = errors.New("test timeout: request took too long") // ErrInvalidConfigValue is returned when a config field has an invalid value. ErrInvalidConfigValue = errors.New("invalid config value") // ErrInvalidTLSClientCertificateConfig is returned when TLS client cert and key paths are inconsistently configured. ErrInvalidTLSClientCertificateConfig = errors.New("TLSClientCertFile and TLSClientKeyFile must both be set or both be empty") )
var DefaultFormEncoder = &FormEncoder{}
DefaultFormEncoder is the default FormEncoder instance.
var DefaultJSONDecoder = &JSONDecoder{
UnmarshalFunc: jsonUnmarshal,
}
DefaultJSONDecoder is the default JSONDecoder instance using the JSON v2 unmarshal function.
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{ UnmarshalFunc: yaml.Unmarshal, }
DefaultYAMLDecoder is the default YAMLDecoder instance using the goccy/go-yaml Unmarshal function.
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 GetBuffer ¶
func GetBuffer() *bytebufferpool.ByteBuffer
GetBuffer retrieves a buffer from the pool.
func IsConnectionError ¶ added in v0.3.13
IsConnectionError reports whether err is a connection-level failure (DNS resolution, TCP connect, TLS handshake).
func IsTimeout ¶ added in v0.3.13
IsTimeout reports whether err is or wraps a timeout error. It checks for context.DeadlineExceeded and net.Error timeout errors.
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 PutBuffer ¶
func PutBuffer(b *bytebufferpool.ByteBuffer)
PutBuffer returns a buffer to the pool.
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 {
BaseURL string // BaseURL is prepended to relative request paths.
Headers *http.Header // Headers contains the default headers sent with each request.
OrderedHeaders *orderedobject.Object[[]string] // OrderedHeaders contains ordered default headers.
Cookies []*http.Cookie // Cookies contains the default cookies sent with each request.
Middlewares []Middleware // Middlewares contains the client-level middleware chain.
TLSConfig *tls.Config // TLSConfig configures TLS settings for the underlying transport.
MaxRetries int // MaxRetries is the maximum number of retry attempts.
RetryStrategy BackoffStrategy // RetryStrategy computes the delay before the next retry.
RetryIf RetryIfFunc // RetryIf decides whether a request should be retried.
HTTPClient *http.Client // HTTPClient is the underlying HTTP client used to send requests.
JSONEncoder Encoder // JSONEncoder encodes JSON request bodies.
JSONDecoder Decoder // JSONDecoder decodes JSON response bodies.
XMLEncoder Encoder // XMLEncoder encodes XML request bodies.
XMLDecoder Decoder // XMLDecoder decodes XML response bodies.
YAMLEncoder Encoder // YAMLEncoder encodes YAML request bodies.
YAMLDecoder Decoder // YAMLDecoder decodes YAML response bodies.
Logger Logger // Logger receives client log output when configured.
// contains filtered or unexported fields
}
Client represents an HTTP client.
func New ¶ added in v0.3.14
func New(opts ...ClientOption) *Client
New creates a Client with functional options applied. It calls Create(nil) to initialize a client with default settings, then applies each option in order.
func (*Client) AddDefaultHeader ¶
AddDefaultHeader adds a default header.
func (*Client) AddMiddleware ¶
func (c *Client) AddMiddleware(middlewares ...Middleware)
AddMiddleware adds a middleware to the client.
func (*Client) ApplyProfile ¶ added in v0.5.0
ApplyProfile applies profile to the client.
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) Connect ¶ added in v0.3.12
func (c *Client) Connect(path string) *RequestBuilder
Connect initiates a CONNECT request.
func (*Client) Custom ¶
func (c *Client) Custom(path, method string) *RequestBuilder
Custom initiates a custom request.
func (*Client) DelDefaultCookie ¶
DelDefaultCookie removes a default cookie from the client.
func (*Client) DelDefaultHeader ¶
DelDefaultHeader removes a default header.
func (*Client) Delete ¶
func (c *Client) Delete(path string) *RequestBuilder
Delete initiates a DELETE request.
func (*Client) EnableHTTP2 ¶ added in v0.5.0
EnableHTTP2 enables HTTP/2 on the underlying HTTP transport.
func (*Client) EnableSession ¶ added in v0.5.0
EnableSession enables cookie and TLS session reuse without replacing existing session stores.
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 := requests.New(
requests.WithBaseURL(server.URL),
requests.WithTimeout(5*time.Second),
)
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.ScanJSON(&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) GetHTTPClient ¶ added in v0.4.0
GetHTTPClient returns the underlying HTTP client in a thread-safe way.
func (*Client) Head ¶
func (c *Client) Head(path string) *RequestBuilder
Head initiates a HEAD request.
func (*Client) InsecureSkipVerify ¶
InsecureSkipVerify sets the TLS configuration to skip certificate verification.
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) RemoveProxy ¶
func (c *Client) RemoveProxy()
RemoveProxy clears any configured proxy, allowing direct connections.
func (*Client) SetAuth ¶
func (c *Client) SetAuth(auth AuthMethod)
SetAuth configures an authentication method for the client.
func (*Client) SetBaseURL ¶
SetBaseURL sets the base URL for the client.
func (*Client) SetCertificates ¶ added in v0.2.3
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
SetCertificates sets the TLS certificates for the client.
func (*Client) SetClientCertificate ¶ added in v0.4.0
SetClientCertificate loads and sets a client certificate and private key from files.
func (*Client) SetClientRootCertificate ¶ added in v0.2.3
SetClientRootCertificate sets the client root certificate for the client.
func (*Client) SetClientRootCertificateFromString ¶ added in v0.2.3
SetClientRootCertificateFromString sets the client root certificate for the client from a string.
func (*Client) SetDefaultAccept ¶
SetDefaultAccept sets the default accept header for the client.
func (*Client) SetDefaultContentType ¶
SetDefaultContentType sets the default content type for the client.
func (*Client) SetDefaultCookie ¶
SetDefaultCookie sets a default cookie for the client.
func (*Client) SetDefaultCookieJar ¶
SetDefaultCookieJar sets the default cookie jar for the client.
func (*Client) SetDefaultCookies ¶
SetDefaultCookies sets the default cookies for the client.
func (*Client) SetDefaultHeader ¶
SetDefaultHeader adds or updates a default header.
func (*Client) SetDefaultHeaders ¶
SetDefaultHeaders sets the default headers for the client.
func (*Client) SetDefaultOrderedHeaders ¶ added in v0.5.0
func (c *Client) SetDefaultOrderedHeaders(headers *orderedobject.Object[[]string])
SetDefaultOrderedHeaders sets ordered default headers for the client.
func (*Client) SetDefaultReferer ¶
SetDefaultReferer sets the default referer for the client.
func (*Client) SetDefaultTimeout ¶
SetDefaultTimeout sets the default timeout for the client.
func (*Client) SetDefaultTransport ¶
func (c *Client) SetDefaultTransport(transport http.RoundTripper)
SetDefaultTransport sets the default transport for the client.
func (*Client) SetDefaultUserAgent ¶
SetDefaultUserAgent sets the default user agent for the client.
func (*Client) SetDialContext ¶ added in v0.5.0
func (c *Client) SetDialContext(dial func(context.Context, string, string) (net.Conn, error)) *Client
SetDialContext sets the dial function on the underlying transport.
func (*Client) SetDialTimeout ¶ added in v0.3.13
SetDialTimeout sets the TCP connection timeout on the underlying transport.
func (*Client) SetHTTPClient ¶
SetHTTPClient sets the HTTP client for the client.
func (*Client) SetIdleConnTimeout ¶ added in v0.3.13
SetIdleConnTimeout sets how long idle connections remain in the pool before being closed.
func (*Client) SetJSONMarshal ¶
SetJSONMarshal sets the JSON marshal function for the client's JSONEncoder.
func (*Client) SetJSONUnmarshal ¶
SetJSONUnmarshal sets the JSON unmarshal function for the client's JSONDecoder.
func (*Client) SetLocalAddr ¶ added in v0.5.0
SetLocalAddr sets the local address used by the default transport dialer.
func (*Client) SetMaxConnsPerHost ¶ added in v0.3.13
SetMaxConnsPerHost sets the maximum total number of connections per host.
func (*Client) SetMaxIdleConns ¶ added in v0.3.13
SetMaxIdleConns sets the maximum number of idle connections across all hosts.
func (*Client) SetMaxIdleConnsPerHost ¶ added in v0.3.13
SetMaxIdleConnsPerHost sets the maximum number of idle connections per host.
func (*Client) SetMaxRetries ¶
SetMaxRetries sets the maximum number of retry attempts.
func (*Client) SetProxies ¶ added in v0.3.13
SetProxies configures multiple proxies with round-robin rotation. Each outgoing request (including retries) picks the next proxy in order.
func (*Client) SetProxy ¶
SetProxy configures the client to use a proxy. Supports http, https, and socks5 proxies.
func (*Client) SetProxyFromEnv ¶ added in v0.3.13
SetProxyFromEnv configures the client to use proxy settings from environment variables (HTTP_PROXY, HTTPS_PROXY, NO_PROXY).
func (*Client) SetProxySelector ¶ added in v0.3.13
SetProxySelector sets a custom proxy selection function matching the http.Transport.Proxy signature. Return nil *url.URL for direct connection.
func (*Client) SetProxyWithBypass ¶ added in v0.3.13
SetProxyWithBypass configures the client to use a proxy with a NO_PROXY bypass list. The bypass parameter is a comma-separated string of hosts that should not use the proxy. Supported formats: domain names, IPs, CIDR subnets, and "*" for wildcard.
func (*Client) SetRedirectPolicy ¶ added in v0.2.3
func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client
SetRedirectPolicy sets the redirect policy for the client.
func (*Client) SetResolver ¶ added in v0.5.0
SetResolver sets the resolver used by the default transport dialer.
func (*Client) SetResponseHeaderTimeout ¶ added in v0.3.13
SetResponseHeaderTimeout sets the time to wait for response headers after the request is sent. This does not include the time to read the response body.
func (*Client) SetRetryIf ¶
func (c *Client) SetRetryIf(retryIf RetryIfFunc) *Client
SetRetryIf sets the custom retry condition function.
func (*Client) SetRetryStrategy ¶
func (c *Client) SetRetryStrategy(strategy BackoffStrategy) *Client
SetRetryStrategy sets the backoff strategy for retries.
func (*Client) SetRootCertificate ¶ added in v0.2.3
SetRootCertificate sets the root certificate for the client.
func (*Client) SetRootCertificateFromString ¶ added in v0.2.3
SetRootCertificateFromString sets the root certificate for the client from a string.
func (*Client) SetTLSConfig ¶
SetTLSConfig sets the TLS configuration for the client.
func (*Client) SetTLSHandshakeTimeout ¶ added in v0.3.13
SetTLSHandshakeTimeout sets the TLS handshake timeout on the underlying transport.
func (*Client) SetTLSServerName ¶ added in v0.4.0
SetTLSServerName sets the TLS server name (SNI) for the client.
func (*Client) SetXMLMarshal ¶
SetXMLMarshal sets the XML marshal function for the client's XMLEncoder.
func (*Client) SetXMLUnmarshal ¶
SetXMLUnmarshal sets the XML unmarshal function for the client's XMLDecoder.
func (*Client) SetYAMLMarshal ¶
SetYAMLMarshal sets the YAML marshal function for the client's YAMLEncoder.
func (*Client) SetYAMLUnmarshal ¶
SetYAMLUnmarshal sets the YAML unmarshal function for the client's YAMLDecoder.
func (*Client) Trace ¶ added in v0.3.12
func (c *Client) Trace(path string) *RequestBuilder
Trace initiates a TRACE request.
type ClientOption ¶ added in v0.3.14
type ClientOption func(*Client)
ClientOption configures a Client. Use with New().
func WithAccept ¶ added in v0.3.14
func WithAccept(accept string) ClientOption
WithAccept sets the default Accept header.
func WithAuth ¶ added in v0.3.14
func WithAuth(auth AuthMethod) ClientOption
WithAuth sets the authentication method for the client.
func WithBaseURL ¶ added in v0.3.14
func WithBaseURL(baseURL string) ClientOption
WithBaseURL sets the base URL for the client.
func WithBasicAuth ¶ added in v0.3.14
func WithBasicAuth(username, password string) ClientOption
WithBasicAuth sets HTTP Basic Authentication credentials.
func WithBearerAuth ¶ added in v0.3.14
func WithBearerAuth(token string) ClientOption
WithBearerAuth sets a Bearer token for authentication.
func WithCertificates ¶ added in v0.3.14
func WithCertificates(certs ...tls.Certificate) ClientOption
WithCertificates sets TLS client certificates.
func WithClientCertificate ¶ added in v0.4.0
func WithClientCertificate(certFile, keyFile string) ClientOption
WithClientCertificate loads and sets a client certificate and key from file paths.
func WithContentType ¶ added in v0.3.14
func WithContentType(contentType string) ClientOption
WithContentType sets the default Content-Type header.
func WithCookieJar ¶ added in v0.3.14
func WithCookieJar(jar *cookiejar.Jar) ClientOption
WithCookieJar sets the cookie jar for the client.
func WithCookies ¶ added in v0.3.14
func WithCookies(cookies map[string]string) ClientOption
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
func WithDialTimeout(d time.Duration) ClientOption
WithDialTimeout sets the TCP connection timeout on the underlying transport.
func WithHTTP2 ¶ added in v0.5.0
func WithHTTP2() ClientOption
WithHTTP2 enables HTTP/2 transport support.
func WithHTTPClient ¶ added in v0.3.14
func WithHTTPClient(httpClient *http.Client) ClientOption
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
func WithHeader(key, value string) ClientOption
WithHeader sets a default header on the client.
func WithHeaders ¶ added in v0.3.14
func WithHeaders(headers *http.Header) ClientOption
WithHeaders sets all default headers on the client.
func WithIdleConnTimeout ¶ added in v0.3.14
func WithIdleConnTimeout(d time.Duration) ClientOption
WithIdleConnTimeout sets how long idle connections remain in the pool.
func WithInsecureSkipVerify ¶ added in v0.3.14
func WithInsecureSkipVerify() ClientOption
WithInsecureSkipVerify configures the client to skip TLS certificate verification.
func WithJSONMarshal ¶ added in v0.3.14
func WithJSONMarshal(marshalFunc func(v any) ([]byte, error)) ClientOption
WithJSONMarshal sets a custom JSON marshal function.
func WithJSONUnmarshal ¶ added in v0.3.14
func WithJSONUnmarshal(unmarshalFunc func(data []byte, v any) error) ClientOption
WithJSONUnmarshal sets a custom JSON unmarshal function.
func WithLocalAddr ¶ added in v0.5.0
func WithLocalAddr(addr net.Addr) ClientOption
WithLocalAddr sets the local address used by the default transport dialer.
func WithLogger ¶ added in v0.3.14
func WithLogger(logger Logger) ClientOption
WithLogger sets the logger for the client.
func WithMaxConnsPerHost ¶ added in v0.3.14
func WithMaxConnsPerHost(n int) ClientOption
WithMaxConnsPerHost sets the maximum total number of connections per host.
func WithMaxIdleConns ¶ added in v0.3.14
func WithMaxIdleConns(n int) ClientOption
WithMaxIdleConns sets the maximum number of idle connections across all hosts.
func WithMaxIdleConnsPerHost ¶ added in v0.3.14
func WithMaxIdleConnsPerHost(n int) ClientOption
WithMaxIdleConnsPerHost sets the maximum number of idle connections per host.
func WithMaxRetries ¶ added in v0.3.14
func WithMaxRetries(maxRetries int) ClientOption
WithMaxRetries sets the maximum number of retry attempts.
func WithMiddleware ¶ added in v0.3.14
func WithMiddleware(middlewares ...Middleware) ClientOption
WithMiddleware adds middleware to the client.
func WithOrderedHeaders ¶ added in v0.5.0
func WithOrderedHeaders(headers *orderedobject.Object[[]string]) ClientOption
WithOrderedHeaders sets ordered default headers on the client.
func WithProfile ¶ added in v0.5.0
func WithProfile(profile Profile) ClientOption
WithProfile applies a coherent client identity profile.
func WithProxy ¶ added in v0.3.14
func WithProxy(proxyURL string) ClientOption
WithProxy sets the proxy URL for the client. Parse errors are silently ignored to maintain the fluent pattern; use Client.SetProxy() directly for error handling.
func WithRedirectPolicy ¶ added in v0.3.14
func WithRedirectPolicy(policies ...RedirectPolicy) ClientOption
WithRedirectPolicy sets the redirect policy for the client.
func WithReferer ¶ added in v0.3.14
func WithReferer(referer string) ClientOption
WithReferer sets the default Referer header.
func WithResolver ¶ added in v0.5.0
func WithResolver(resolver *net.Resolver) ClientOption
WithResolver sets the resolver used by the default transport dialer.
func WithResponseHeaderTimeout ¶ added in v0.3.14
func WithResponseHeaderTimeout(d time.Duration) ClientOption
WithResponseHeaderTimeout sets the time to wait for response headers.
func WithRetryIf ¶ added in v0.3.14
func WithRetryIf(retryIf RetryIfFunc) ClientOption
WithRetryIf sets the custom retry condition function.
func WithRetryStrategy ¶ added in v0.3.14
func WithRetryStrategy(strategy BackoffStrategy) ClientOption
WithRetryStrategy sets the backoff strategy for retries.
func WithRootCertificate ¶ added in v0.3.14
func WithRootCertificate(pemFilePath string) ClientOption
WithRootCertificate sets the root certificate from a PEM file path.
func WithRootCertificateFromString ¶ added in v0.3.14
func WithRootCertificateFromString(pemCerts string) ClientOption
WithRootCertificateFromString sets the root certificate from a PEM string.
func WithSession ¶ added in v0.5.0
func WithSession() ClientOption
WithSession enables cookie and TLS session reuse.
func WithTLSConfig ¶ added in v0.3.14
func WithTLSConfig(config *tls.Config) ClientOption
WithTLSConfig sets the TLS configuration for the client.
func WithTLSHandshakeTimeout ¶ added in v0.3.14
func WithTLSHandshakeTimeout(d time.Duration) ClientOption
WithTLSHandshakeTimeout sets the TLS handshake timeout on the underlying transport.
func WithTLSServerName ¶ added in v0.4.0
func WithTLSServerName(serverName string) ClientOption
WithTLSServerName sets the TLS server name (SNI).
func WithTimeout ¶ added in v0.3.14
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout sets the default timeout for the client.
func WithTransport ¶ added in v0.3.14
func WithTransport(transport http.RoundTripper) ClientOption
WithTransport sets the HTTP transport for the client.
func WithUserAgent ¶ added in v0.3.14
func WithUserAgent(userAgent string) ClientOption
WithUserAgent sets the default User-Agent header.
func WithXMLMarshal ¶ added in v0.3.14
func WithXMLMarshal(marshalFunc func(v any) ([]byte, error)) ClientOption
WithXMLMarshal sets a custom XML marshal function.
func WithXMLUnmarshal ¶ added in v0.3.14
func WithXMLUnmarshal(unmarshalFunc func(data []byte, v any) error) ClientOption
WithXMLUnmarshal sets a custom XML unmarshal function.
func WithYAMLMarshal ¶ added in v0.3.14
func WithYAMLMarshal(marshalFunc func(v any) ([]byte, error)) ClientOption
WithYAMLMarshal sets a custom YAML marshal function.
func WithYAMLUnmarshal ¶ added in v0.3.14
func WithYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error) ClientOption
WithYAMLUnmarshal sets a custom YAML unmarshal function.
type Config ¶
type Config struct {
BaseURL string // BaseURL is the base URL for requests made by this client.
Headers *http.Header // Headers contains the default headers sent with each request.
OrderedHeaders *orderedobject.Object[[]string] // OrderedHeaders contains ordered default headers.
Cookies map[string]string // Cookies contains the default cookies sent with each request.
Timeout time.Duration // Timeout is the default request timeout.
CookieJar *cookiejar.Jar // CookieJar stores and sends cookies for the client.
Middlewares []Middleware // Middlewares contains the middleware stack for request and response handling.
TLSConfig *tls.Config // TLSConfig configures TLS settings for the client.
TLSClientCertFile string // TLSClientCertFile is the path to the client certificate file.
TLSClientKeyFile string // TLSClientKeyFile is the path to the client private key file.
TLSServerName string // TLSServerName is the TLS server name used for SNI.
Transport http.RoundTripper // Transport is the custom transport used by the client.
MaxRetries int // MaxRetries is the maximum number of retry attempts.
RetryStrategy BackoffStrategy // RetryStrategy computes the delay before the next retry.
RetryIf RetryIfFunc // RetryIf decides whether a request should be retried.
Logger Logger // Logger receives client log output when configured.
HTTP2 bool // HTTP2 enables HTTP/2 on the default HTTP transport.
Resolver *net.Resolver // Resolver customizes name resolution for the default transport dialer.
// DialContext is the dial function used by the default transport.
DialContext func(context.Context, string, string) (net.Conn, error)
LocalAddr net.Addr // LocalAddr is the local address used by the default transport dialer.
// Transport-level timeouts.
DialTimeout time.Duration // DialTimeout is the TCP connection timeout.
TLSHandshakeTimeout time.Duration // TLSHandshakeTimeout is the TLS handshake timeout.
ResponseHeaderTimeout time.Duration // ResponseHeaderTimeout is the time to the first response byte.
// Connection pool settings.
MaxIdleConns int // MaxIdleConns is the maximum number of idle connections across all hosts.
MaxIdleConnsPerHost int // MaxIdleConnsPerHost is the maximum number of idle connections per host.
MaxConnsPerHost int // MaxConnsPerHost is the maximum number of connections per host.
IdleConnTimeout time.Duration // IdleConnTimeout is how long idle connections remain open.
}
Config sets up the initial configuration for the HTTP client.
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 {
UnmarshalFunc func(data []byte, v any) error // UnmarshalFunc unmarshals 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 NoProxy ¶ added in v0.3.13
type NoProxy struct {
// contains filtered or unexported fields
}
NoProxy holds parsed bypass rules for proxy exclusion.
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) Body ¶
func (b *RequestBuilder) Body(body any) *RequestBuilder
Body sets the request body.
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, stream callbacks, 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.
func (*RequestBuilder) Files ¶
func (b *RequestBuilder) Files(files ...*File) *RequestBuilder
Files sets multiple files at once.
func (*RequestBuilder) Form ¶
func (b *RequestBuilder) Form(v any) *RequestBuilder
Form sets form fields and files for the request.
func (*RequestBuilder) FormField ¶
func (b *RequestBuilder) FormField(key, val string) *RequestBuilder
FormField adds or updates a form field.
func (*RequestBuilder) FormFields ¶
func (b *RequestBuilder) FormFields(fields any) *RequestBuilder
FormFields sets multiple form fields at once.
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) JSONBody ¶ added in v0.2.2
func (b *RequestBuilder) JSONBody(v any) *RequestBuilder
JSONBody sets the request body as JSON.
func (*RequestBuilder) MaxRetries ¶
func (b *RequestBuilder) MaxRetries(maxRetries int) *RequestBuilder
MaxRetries sets the maximum number of retry attempts.
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.
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) RawBody ¶
func (b *RequestBuilder) RawBody(v []byte) *RequestBuilder
RawBody sets the request body as raw bytes.
func (*RequestBuilder) Referer ¶
func (b *RequestBuilder) Referer(referer string) *RequestBuilder
Referer sets the Referer header for the request.
func (*RequestBuilder) RetryIf ¶
func (b *RequestBuilder) RetryIf(retryIf RetryIfFunc) *RequestBuilder
RetryIf sets the custom retry condition function.
func (*RequestBuilder) RetryStrategy ¶
func (b *RequestBuilder) RetryStrategy(strategy BackoffStrategy) *RequestBuilder
RetryStrategy sets the backoff strategy for retries.
func (*RequestBuilder) Send ¶
func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)
Send executes the HTTP request.
func (*RequestBuilder) Stream ¶ added in v0.2.0
func (b *RequestBuilder) Stream(callback StreamCallback) *RequestBuilder
Stream sets the stream callback for the request.
func (*RequestBuilder) StreamDone ¶ added in v0.2.1
func (b *RequestBuilder) StreamDone(callback StreamDoneCallback) *RequestBuilder
StreamDone sets the done callback for the request.
func (*RequestBuilder) StreamErr ¶ added in v0.2.1
func (b *RequestBuilder) StreamErr(callback StreamErrCallback) *RequestBuilder
StreamErr sets the error callback for the request.
func (*RequestBuilder) TextBody ¶
func (b *RequestBuilder) TextBody(v string) *RequestBuilder
TextBody sets the request body as plain text.
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) XMLBody ¶
func (b *RequestBuilder) XMLBody(v any) *RequestBuilder
XMLBody sets the request body as XML.
func (*RequestBuilder) YAMLBody ¶
func (b *RequestBuilder) YAMLBody(v any) *RequestBuilder
YAMLBody sets the request body as YAML.
type Response ¶
type Response struct {
RawResponse *http.Response // RawResponse is the underlying HTTP response.
BodyBytes []byte // BodyBytes contains the buffered response body for non-streaming responses.
Context context.Context // Context is the request context associated with the response.
Client *Client // Client is the client that created the response.
// contains filtered or unexported fields
}
Response represents an HTTP response.
func NewResponse ¶
func NewResponse( ctx context.Context, resp *http.Response, client *Client, stream StreamCallback, streamErr StreamErrCallback, streamDone StreamDoneCallback, ) (*Response, error)
NewResponse creates a new wrapped response object, leveraging the buffer pool for efficient memory usage.
func (*Response) Attempts ¶ added in v0.5.0
Attempts returns the total number of transport attempts, including the first request.
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) 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) 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 RetryConfig ¶
type RetryConfig struct {
MaxRetries int // MaxRetries is the maximum number of retry attempts.
Strategy BackoffStrategy // Strategy computes the delay before the next retry.
RetryIf RetryIfFunc // RetryIf decides whether a request should be retried.
}
RetryConfig defines the configuration for retrying requests.
type RetryIfFunc ¶
RetryIfFunc defines the function signature for retry conditions.
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 StreamCallback ¶ added in v0.2.0
StreamCallback handles a streamed response chunk.
type StreamDoneCallback ¶ added in v0.2.0
type StreamDoneCallback func()
StreamDoneCallback runs after streaming finishes.
type StreamErrCallback ¶ added in v0.2.0
type StreamErrCallback func(error)
StreamErrCallback handles a streaming read error.
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 {
UnmarshalFunc func(data []byte, v any) error // UnmarshalFunc unmarshals 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. |