requests

package module
v0.3.18 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 31 Imported by: 1

README

Golang Requests Library

The Requests library simplifies the way you make HTTP requests in Go. It provides an easy-to-use interface for sending requests and handling responses, reducing the boilerplate code typically associated with the net/http package.

Quick Start

Begin by installing the Requests library:

go get github.com/kaptinlin/requests

Creating a new HTTP client and making a request is straightforward:

package main

import (
    "context"
    "log"
    "time"

    "github.com/kaptinlin/requests"
)

func main() {
    // Create a client with functional options (recommended)
    client := requests.New(
        requests.WithBaseURL("http://example.com"),
        requests.WithTimeout(30 * time.Second),
    )

    // Perform a GET request
    resp, err := client.Get("/resource").Send(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Close()

    log.Println(resp.String())
}

Overview

Client

The Client struct is your gateway to making HTTP requests. You can configure it to your needs, setting default headers, cookies, timeout durations, and more.

Creating a Client
// Functional options (recommended)
client := requests.New(
    requests.WithBaseURL("http://example.com"),
    requests.WithTimeout(5 * time.Second),
    requests.WithContentType("application/json"),
    requests.WithBearerAuth("my-token"),
    requests.WithMaxRetries(3),
)

// Short form for URL-only clients
client = requests.URL("http://example.com")

// Struct-based configuration (for HTTP/2 or full control)
client = requests.Create(&requests.Config{
    BaseURL: "http://example.com",
    Timeout: 5 * time.Second,
    HTTP2:   true,
})
Passing to Downstream Libraries

The New() constructor returns *Client in a single expression, making it easy to pass into other libraries:

scorer := NewVoyageScorer(
    WithHTTPClient(requests.New(
        requests.WithTimeout(60 * time.Second),
        requests.WithMaxRetries(3),
        requests.WithBearerAuth("token"),
    )),
)

For more details, see docs/client.md.

Request

The library provides a RequestBuilder to construct and dispatch HTTP requests. Here are examples of performing various types of requests, including adding query parameters, setting headers, and attaching a body to your requests.

GET Request

To retrieve data from a specific resource:

resp, err := client.Get("/path").
    Query("search", "query").
    Header("Accept", "application/json").
    Send(context.Background())
POST Request

To submit data to be processed to a specific resource:

resp, err := client.Post("/path").
    Header("Content-Type", "application/json").
    JSONBody(map[string]any{"key": "value"}).
    Send(context.Background())
PUT Request

To replace all current representations of the target resource with the request payload:

resp, err := client.Put("/articles/{article_id}").
    PathParam("article_id", "123456").
    JSONBody(map[string]any{"updatedKey": "newValue"}).
    Send(context.Background())
DELETE Request

To remove all current representations of the target resource:

resp, err := client.Delete("/articles/{article_id}").
    PathParam("article_id", "123456").
    Send(context.Background())

For more details, visit docs/request.md.

Response

Handling responses is crucial in determining the outcome of your HTTP requests. The Requests library makes it easy to check status codes, read headers, and parse the body content.

Example

Parsing JSON response into a Go struct:

type APIResponse struct {
    Data string `json:"data"`
}

var apiResp APIResponse
if err := resp.ScanJSON(&apiResp); err != nil {
    log.Fatal(err)
}

log.Printf("Status Code: %d\n", resp.StatusCode())
log.Printf("Response Data: %s\n", apiResp.Data)

This example demonstrates how to unmarshal a JSON response and check the HTTP status code.

Additional status helpers: IsSuccess(), IsError(), IsClientError(), IsServerError(), IsRedirect().

For more on handling responses, see docs/response.md.

Proxy

Configure proxy settings with optional bypass rules:

// Single proxy
client.SetProxy("http://proxy:8080")

// Multiple proxies with round-robin rotation (retries auto-rotate)
client.SetProxies("http://proxy1:8080", "http://proxy2:8080", "socks5://proxy3:1080")

// Proxy with NO_PROXY bypass list
client.SetProxyWithBypass("http://proxy:8080", "localhost, .internal.com, 10.0.0.0/8")

// Use environment variables (HTTP_PROXY, HTTPS_PROXY, NO_PROXY)
client.SetProxyFromEnv()
Redirect Policies

Control redirect behavior including browser-like method downgrade:

// Smart redirect: downgrades POST→GET on 301/302/303, strips sensitive headers cross-host
client.SetRedirectPolicy(requests.NewSmartRedirectPolicy(10))

For more details, see docs/client.md.

Transport Timeouts & Connection Pool

Fine-grained control over request phases and connection pooling:

client := requests.Create(&requests.Config{
    BaseURL:               "https://api.example.com",
    Timeout:               60 * time.Second,  // overall deadline
    DialTimeout:           5 * time.Second,   // TCP connect
    TLSHandshakeTimeout:   5 * time.Second,   // TLS negotiation
    ResponseHeaderTimeout: 10 * time.Second,  // time to first byte
    MaxIdleConnsPerHost:   10,                // connection pool tuning
})
Error Introspection

Classify errors without manual type assertion chains:

_, err := client.Get("/resource").Send(ctx)
if requests.IsTimeout(err) {
    // Handle timeout (context deadline, net timeout)
}
if requests.IsConnectionError(err) {
    // Handle connection failure (DNS, TCP, TLS)
}

Additional Resources

  • Logging: Learn how to configure logging for your requests. See docs/logging.md.
  • Middleware: Extend functionality with custom middleware. See docs/middleware.md.
  • Retry Mechanism: Implement retry strategies for transient errors. See docs/retry.md.
  • Stream Support: Utilize streaming for real-time data processing. See docs/stream.md.

Credits

This library was inspired by and built upon the work of several other HTTP client libraries:

How to Contribute

Contributions to the requests package are welcome. If you'd like to contribute, please follow the contribution guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package requests provides a fluent HTTP client library for Go.

Index

Constants

View Source
const DirPermissions = 0o750
View Source
const MaxStreamBufferSize = 512 * 1024

MaxStreamBufferSize is the maximum size of the buffer used for streaming.

Variables

View Source
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")

	// 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")
)
View Source
var DefaultFormEncoder = &FormEncoder{}

DefaultFormEncoder is the default FormEncoder instance.

View Source
var DefaultJSONDecoder = &JSONDecoder{
	UnmarshalFunc: jsonUnmarshal,
}

DefaultJSONDecoder is the default JSONDecoder instance using the JSON v2 unmarshal function.

View Source
var DefaultJSONEncoder = &JSONEncoder{
	MarshalFunc: jsonMarshal,
}

DefaultJSONEncoder is the default JSONEncoder instance using the JSON v2 marshal function.

View Source
var DefaultXMLDecoder = &XMLDecoder{
	UnmarshalFunc: xml.Unmarshal,
}

DefaultXMLDecoder is the default XMLDecoder instance using the standard xml.Unmarshal function.

View Source
var DefaultXMLEncoder = &XMLEncoder{
	MarshalFunc: xml.Marshal,
}

DefaultXMLEncoder is the default XMLEncoder instance using the standard xml.Marshal function.

View Source
var DefaultYAMLDecoder = &YAMLDecoder{
	UnmarshalFunc: yaml.Unmarshal,
}

DefaultYAMLDecoder is the default YAMLDecoder instance using the goccy/go-yaml Unmarshal function.

View Source
var DefaultYAMLEncoder = &YAMLEncoder{
	MarshalFunc: yaml.Marshal,
}

DefaultYAMLEncoder is the default YAMLEncoder instance using the goccy/go-yaml Marshal function.

Functions

func DefaultBackoffStrategy

func DefaultBackoffStrategy(delay time.Duration) func(int) time.Duration

DefaultBackoffStrategy provides a simple constant delay between retries.

func DefaultRetryIf

func DefaultRetryIf(req *http.Request, resp *http.Response, err error) bool

DefaultRetryIf is a simple retry condition that retries on 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

func IsConnectionError(err error) bool

IsConnectionError reports whether err is a connection-level failure (DNS resolution, TCP connect, TLS handshake).

func IsTimeout added in v0.3.13

func IsTimeout(err error) bool

IsTimeout reports whether err is or wraps a timeout error. It checks for context.DeadlineExceeded and net.Error timeout errors.

func LinearBackoffStrategy

func LinearBackoffStrategy(initialInterval time.Duration) func(int) time.Duration

LinearBackoffStrategy increases the delay linearly with each retry attempt. The delay increments by `initialInterval` with each attempt.

func PutBuffer

func PutBuffer(b *bytebufferpool.ByteBuffer)

PutBuffer returns a buffer to the pool.

func RandomProxies added in v0.3.13

func RandomProxies(proxyURLs ...string) (func(*http.Request) (*url.URL, error), error)

RandomProxies returns a proxy function that selects a random proxy for each request. Safe for concurrent use.

func RoundRobinProxies added in v0.3.13

func RoundRobinProxies(proxyURLs ...string) (func(*http.Request) (*url.URL, error), error)

RoundRobinProxies returns a proxy function that cycles through proxies in order. 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.

func (*AllowRedirectPolicy) Apply added in v0.2.3

func (a *AllowRedirectPolicy) Apply(req *http.Request, via []*http.Request) error

Apply allows redirects up to the configured limit, returning ErrTooManyRedirects if exceeded.

type AuthMethod

type AuthMethod interface {
	Apply(req *http.Request)
	Valid() bool
}

AuthMethod defines the interface for applying authentication strategies to requests.

type BackoffStrategy

type BackoffStrategy func(attempt int) time.Duration

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 ±fraction of the base delay. For example, a fraction of 0.25 means ±25% jitter.

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth represents HTTP Basic Authentication credentials.

func (BasicAuth) Apply

func (b BasicAuth) Apply(req *http.Request)

Apply adds the Basic Auth credentials to the request.

func (BasicAuth) Valid

func (b BasicAuth) Valid() bool

Valid checks if the Basic Auth credentials are present.

type BearerAuth

type BearerAuth struct {
	Token string
}

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
	Headers       *http.Header
	Cookies       []*http.Cookie
	Middlewares   []Middleware
	TLSConfig     *tls.Config
	MaxRetries    int             // Maximum number of retry attempts
	RetryStrategy BackoffStrategy // The backoff strategy function
	RetryIf       RetryIfFunc     // Custom function to determine retry based on request and response
	HTTPClient    *http.Client
	JSONEncoder   Encoder
	JSONDecoder   Decoder
	XMLEncoder    Encoder
	XMLDecoder    Decoder
	YAMLEncoder   Encoder
	YAMLDecoder   Decoder
	Logger        Logger
	// contains filtered or unexported fields
}

Client represents an HTTP client.

func Create

func Create(config *Config) *Client

Create initializes a new HTTP client with the given configuration.

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 URL

func URL(baseURL string) *Client

URL creates a new HTTP client with the given base URL.

func (*Client) AddDefaultHeader

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

AddDefaultHeader adds a default header.

func (*Client) AddMiddleware

func (c *Client) AddMiddleware(middlewares ...Middleware)

AddMiddleware adds a middleware to the client.

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

func (c *Client) DelDefaultCookie(name string)

DelDefaultCookie removes a default cookie from the client.

func (*Client) DelDefaultHeader

func (c *Client) DelDefaultHeader(key string)

DelDefaultHeader removes a default header.

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.

func (*Client) Head

func (c *Client) Head(path string) *RequestBuilder

Head initiates a HEAD request.

func (*Client) InsecureSkipVerify

func (c *Client) InsecureSkipVerify() *Client

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) Put

func (c *Client) Put(path string) *RequestBuilder

Put initiates a PUT 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

func (c *Client) SetBaseURL(baseURL string)

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) SetClientRootCertificate added in v0.2.3

func (c *Client) SetClientRootCertificate(pemFilePath string) *Client

SetClientRootCertificate sets the client root certificate for the client.

func (*Client) SetClientRootCertificateFromString added in v0.2.3

func (c *Client) SetClientRootCertificateFromString(pemCerts string) *Client

SetClientRootCertificateFromString sets the client root certificate for the client from a string.

func (*Client) SetDefaultAccept

func (c *Client) SetDefaultAccept(accept string)

SetDefaultAccept sets the default accept header for the client.

func (*Client) SetDefaultContentType

func (c *Client) SetDefaultContentType(contentType string)

SetDefaultContentType sets the default content type for the client.

func (*Client) SetDefaultCookie

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

SetDefaultCookie sets a default cookie for the client.

func (*Client) SetDefaultCookieJar

func (c *Client) SetDefaultCookieJar(jar *cookiejar.Jar)

SetDefaultCookieJar sets the default cookie jar for the client.

func (*Client) SetDefaultCookies

func (c *Client) SetDefaultCookies(cookies map[string]string)

SetDefaultCookies sets the default cookies for the client.

func (*Client) SetDefaultHeader

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

SetDefaultHeader adds or updates a default header.

func (*Client) SetDefaultHeaders

func (c *Client) SetDefaultHeaders(headers *http.Header)

SetDefaultHeaders sets the default headers for the client.

func (*Client) SetDefaultReferer

func (c *Client) SetDefaultReferer(referer string)

SetDefaultReferer sets the default referer for the client.

func (*Client) SetDefaultTimeout

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

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

func (c *Client) SetDefaultUserAgent(userAgent string)

SetDefaultUserAgent sets the default user agent for the client.

func (*Client) SetDialTimeout added in v0.3.13

func (c *Client) SetDialTimeout(d time.Duration) *Client

SetDialTimeout sets the TCP connection timeout on the underlying transport.

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(httpClient *http.Client)

SetHTTPClient sets the HTTP client for the client.

func (*Client) SetIdleConnTimeout added in v0.3.13

func (c *Client) SetIdleConnTimeout(d time.Duration) *Client

SetIdleConnTimeout sets how long idle connections remain in the pool before being closed.

func (*Client) SetJSONMarshal

func (c *Client) SetJSONMarshal(marshalFunc func(v any) ([]byte, error))

SetJSONMarshal sets the JSON marshal function for the client's JSONEncoder.

func (*Client) SetJSONUnmarshal

func (c *Client) SetJSONUnmarshal(unmarshalFunc func(data []byte, v any) error)

SetJSONUnmarshal sets the JSON unmarshal function for the client's JSONDecoder.

func (*Client) SetLogger

func (c *Client) SetLogger(logger Logger) *Client

SetLogger sets logger instance in client.

func (*Client) SetMaxConnsPerHost added in v0.3.13

func (c *Client) SetMaxConnsPerHost(n int) *Client

SetMaxConnsPerHost sets the maximum total number of connections per host.

func (*Client) SetMaxIdleConns added in v0.3.13

func (c *Client) SetMaxIdleConns(n int) *Client

SetMaxIdleConns sets the maximum number of idle connections across all hosts.

func (*Client) SetMaxIdleConnsPerHost added in v0.3.13

func (c *Client) SetMaxIdleConnsPerHost(n int) *Client

SetMaxIdleConnsPerHost sets the maximum number of idle connections per host.

func (*Client) SetMaxRetries

func (c *Client) SetMaxRetries(maxRetries int) *Client

SetMaxRetries sets the maximum number of retry attempts.

func (*Client) SetProxies added in v0.3.13

func (c *Client) SetProxies(proxyURLs ...string) error

SetProxies configures multiple proxies with round-robin rotation. Each outgoing request (including retries) picks the next proxy in order.

func (*Client) SetProxy

func (c *Client) SetProxy(proxyURL string) error

SetProxy configures the client to use a proxy. Supports http, https, and socks5 proxies.

func (*Client) SetProxyFromEnv added in v0.3.13

func (c *Client) SetProxyFromEnv() error

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

func (c *Client) SetProxySelector(selector func(*http.Request) (*url.URL, error)) error

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

func (c *Client) SetProxyWithBypass(proxyURL, bypass string) error

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) SetResponseHeaderTimeout added in v0.3.13

func (c *Client) SetResponseHeaderTimeout(d time.Duration) *Client

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

func (c *Client) SetRootCertificate(pemFilePath string) *Client

SetRootCertificate sets the root certificate for the client.

func (*Client) SetRootCertificateFromString added in v0.2.3

func (c *Client) SetRootCertificateFromString(pemCerts string) *Client

SetRootCertificateFromString sets the root certificate for the client from a string.

func (*Client) SetTLSConfig

func (c *Client) SetTLSConfig(config *tls.Config) *Client

SetTLSConfig sets the TLS configuration for the client.

func (*Client) SetTLSHandshakeTimeout added in v0.3.13

func (c *Client) SetTLSHandshakeTimeout(d time.Duration) *Client

SetTLSHandshakeTimeout sets the TLS handshake timeout on the underlying transport.

func (*Client) SetXMLMarshal

func (c *Client) SetXMLMarshal(marshalFunc func(v any) ([]byte, error))

SetXMLMarshal sets the XML marshal function for the client's XMLEncoder.

func (*Client) SetXMLUnmarshal

func (c *Client) SetXMLUnmarshal(unmarshalFunc func(data []byte, v any) error)

SetXMLUnmarshal sets the XML unmarshal function for the client's XMLDecoder.

func (*Client) SetYAMLMarshal

func (c *Client) SetYAMLMarshal(marshalFunc func(v any) ([]byte, error))

SetYAMLMarshal sets the YAML marshal function for the client's YAMLEncoder.

func (*Client) SetYAMLUnmarshal

func (c *Client) SetYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error)

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 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 WithDialTimeout added in v0.3.14

func WithDialTimeout(d time.Duration) ClientOption

WithDialTimeout sets the TCP connection timeout on the underlying transport.

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 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 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 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 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 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            // The base URL for all requests made by this client.
	Headers       *http.Header      // Default headers to be sent with each request.
	Cookies       map[string]string // Default Cookies to be sent with each request.
	Timeout       time.Duration     // Timeout for requests.
	CookieJar     *cookiejar.Jar    // Cookie jar for the client.
	Middlewares   []Middleware      // Middleware stack for request/response manipulation.
	TLSConfig     *tls.Config       // TLS configuration for the client.
	Transport     http.RoundTripper // Custom transport for the client.
	MaxRetries    int               // Maximum number of retry attempts
	RetryStrategy BackoffStrategy   // The backoff strategy function
	RetryIf       RetryIfFunc       // Custom function to determine retry based on request and response
	Logger        Logger            // Logger instance for the client
	HTTP2         bool              // Whether to use HTTP/2. Transport takes priority over HTTP2 if both are set.

	// Transport-level timeouts (applied to http.Transport)
	DialTimeout           time.Duration // TCP connection timeout
	TLSHandshakeTimeout   time.Duration // TLS handshake timeout
	ResponseHeaderTimeout time.Duration // Time to first response byte

	// Connection pool settings (applied to http.Transport)
	MaxIdleConns        int           // Max idle connections across all hosts (0 = default 100)
	MaxIdleConnsPerHost int           // Max idle connections per host (0 = default 2)
	MaxConnsPerHost     int           // Max total connections per host (0 = no limit)
	IdleConnTimeout     time.Duration // How long idle connections live (0 = default 90s)
}

Config sets up the initial configuration for the HTTP client.

type CustomAuth

type CustomAuth struct {
	Header string
}

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 Decoder

type Decoder interface {
	Decode(r io.Reader, v any) error
}

Decoder decodes data from an io.Reader into a value.

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(v any) (io.Reader, error)
	ContentType() string
}

Encoder encodes values into an io.Reader format with a specific content type.

type File

type File struct {
	Name     string        // Form field name
	FileName string        // File name
	Content  io.ReadCloser // 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

func (f *File) SetFileName(fileName string)

SetFileName sets the file name.

func (*File) SetName

func (f *File) SetName(name string)

SetName sets the form field name.

type FormEncoder

type FormEncoder struct{}

FormEncoder handles encoding of form data.

func (*FormEncoder) Encode

func (e *FormEncoder) Encode(v any) (io.Reader, error)

Encode encodes the given value into URL-encoded form data.

type JSONDecoder

type JSONDecoder struct {
	UnmarshalFunc func(data []byte, v any) error
}

JSONDecoder handles decoding of JSON data.

func (*JSONDecoder) Decode

func (d *JSONDecoder) Decode(r io.Reader, v any) error

Decode reads the data from the reader and unmarshals it into the provided value.

type JSONEncoder

type JSONEncoder struct {
	MarshalFunc func(v any) ([]byte, error)
}

JSONEncoder handles encoding of JSON data.

func (*JSONEncoder) ContentType

func (e *JSONEncoder) ContentType() string

ContentType returns the content type for JSON data.

func (*JSONEncoder) Encode

func (e *JSONEncoder) Encode(v any) (io.Reader, error)

Encode marshals the provided value into JSON format.

type Level

type Level int

Level is a type that represents the log level.

const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
)

The levels of logs.

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.

func NewDefaultLogger added in v0.1.1

func NewDefaultLogger(output io.Writer, level Level) Logger

NewDefaultLogger creates a new `DefaultLogger` with the given output and log level.

type Middleware

type Middleware func(next MiddlewareHandlerFunc) MiddlewareHandlerFunc

Middleware defines a function that takes an http.Request and returns an http.Response and an error. It wraps around a next function call, which can be another middleware or the final transport layer call.

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc func(req *http.Request) (*http.Response, error)

MiddlewareHandlerFunc defines a function that takes an http.Request and returns an http.Response and an error.

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.

func (*ProhibitRedirectPolicy) Apply added in v0.2.3

func (p *ProhibitRedirectPolicy) Apply(req *http.Request, via []*http.Request) error

Apply rejects all redirects by returning ErrAutoRedirectDisabled.

type RedirectPolicy added in v0.2.3

type RedirectPolicy interface {
	Apply(req *http.Request, via []*http.Request) error
}

RedirectPolicy is an interface that defines the Apply method.

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.

func (*RedirectSpecifiedDomainPolicy) Apply added in v0.2.3

Apply checks if the redirect target domain is in the allowed domains list.

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, 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 method for 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) 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
	BodyBytes   []byte
	Context     context.Context
	Client      *Client
	// 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) Body

func (r *Response) Body() []byte

Body returns the response body as a byte slice.

func (*Response) Close

func (r *Response) Close() error

Close closes the response body.

func (*Response) ContentLength

func (r *Response) ContentLength() int

ContentLength returns the length of the response body.

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the value of the "Content-Type" header.

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies parses and returns the cookies set in the response.

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the response headers.

func (*Response) IsClientError added in v0.3.13

func (r *Response) IsClientError() bool

IsClientError checks if the response status code indicates a client error (400 - 499).

func (*Response) IsContentType

func (r *Response) IsContentType(contentType string) bool

IsContentType checks if the response Content-Type header matches a given content type.

func (*Response) IsEmpty

func (r *Response) IsEmpty() bool

IsEmpty checks if the response body is empty.

func (*Response) IsError added in v0.3.13

func (r *Response) IsError() bool

IsError checks if the response status code indicates an error (>= 400).

func (*Response) IsJSON

func (r *Response) IsJSON() bool

IsJSON checks if the response Content-Type indicates JSON.

func (*Response) IsRedirect added in v0.3.13

func (r *Response) IsRedirect() bool

IsRedirect checks if the response status code indicates a redirect (300 - 399).

func (*Response) IsServerError added in v0.3.13

func (r *Response) IsServerError() bool

IsServerError checks if the response status code indicates a server error (>= 500).

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess checks if the response status code indicates success (200 - 299).

func (*Response) IsXML

func (r *Response) IsXML() bool

IsXML checks if the response Content-Type indicates XML.

func (*Response) IsYAML

func (r *Response) IsYAML() bool

IsYAML checks if the response Content-Type indicates YAML.

func (*Response) Lines added in v0.2.4

func (r *Response) Lines() iter.Seq[[]byte]

Lines returns an iterator that yields each line of the response body as []byte. This method is available in Go 1.23+ and provides a convenient way to iterate over response lines without loading the entire body into memory. The iterator will automatically handle the scanning and yield each line. Note: This method is designed for non-streaming responses and will return an empty iterator for streaming responses.

func (*Response) Location

func (r *Response) Location() (*url.URL, error)

Location returns the URL redirected address.

func (*Response) Save

func (r *Response) Save(v any) error

Save saves the response body to a file or io.Writer.

func (*Response) Scan

func (r *Response) Scan(v any) error

Scan attempts to unmarshal the response body based on its content type.

func (*Response) ScanJSON

func (r *Response) ScanJSON(v any) error

ScanJSON unmarshals the response body into a struct via JSON decoding.

func (*Response) ScanXML

func (r *Response) ScanXML(v any) error

ScanXML unmarshals the response body into a struct via XML decoding.

func (*Response) ScanYAML

func (r *Response) ScanYAML(v any) error

ScanYAML unmarshals the response body into a struct via YAML decoding.

func (*Response) Status

func (r *Response) Status() string

Status returns the status string of the response (e.g., "200 OK").

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code of the response.

func (*Response) String

func (r *Response) String() string

String returns the response body as a string.

func (*Response) URL

func (r *Response) URL() *url.URL

URL returns the request URL that elicited the response.

type RetryConfig

type RetryConfig struct {
	MaxRetries int             // Maximum number of retry attempts
	Strategy   BackoffStrategy // The backoff strategy function
	RetryIf    RetryIfFunc     // Custom function to determine retry based on request and response
}

RetryConfig defines the configuration for retrying requests.

type RetryIfFunc

type RetryIfFunc func(req *http.Request, resp *http.Response, err error) bool

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.

func (*SmartRedirectPolicy) Apply added in v0.3.13

func (s *SmartRedirectPolicy) Apply(req *http.Request, via []*http.Request) error

Apply enforces the redirect limit, performs method downgrade for 301/302/303, and strips sensitive headers on cross-host or HTTPS-to-HTTP redirects.

type StreamCallback added in v0.2.0

type StreamCallback func([]byte) error

StreamCallback is a callback function that is called when data is received.

type StreamDoneCallback added in v0.2.0

type StreamDoneCallback func()

StreamDoneCallback is a callback function that is called when the stream is done.

type StreamErrCallback added in v0.2.0

type StreamErrCallback func(error)

StreamErrCallback is a callback function that is called when an error occurs.

type XMLDecoder

type XMLDecoder struct {
	UnmarshalFunc func(data []byte, v any) error
}

XMLDecoder handles decoding of XML data.

func (*XMLDecoder) Decode

func (d *XMLDecoder) Decode(r io.Reader, v any) error

Decode reads the data from the reader and unmarshals it into the provided value.

type XMLEncoder

type XMLEncoder struct {
	MarshalFunc func(v any) ([]byte, error)
}

XMLEncoder handles encoding of XML data.

func (*XMLEncoder) ContentType

func (e *XMLEncoder) ContentType() string

ContentType returns the content type for XML data.

func (*XMLEncoder) Encode

func (e *XMLEncoder) Encode(v any) (io.Reader, error)

Encode marshals the provided value into XML format.

type YAMLDecoder

type YAMLDecoder struct {
	UnmarshalFunc func(data []byte, v any) error
}

YAMLDecoder handles decoding of YAML data.

func (*YAMLDecoder) Decode

func (d *YAMLDecoder) Decode(r io.Reader, v any) error

Decode reads the data from the reader and unmarshals it into the provided value.

type YAMLEncoder

type YAMLEncoder struct {
	MarshalFunc func(v any) ([]byte, error)
}

YAMLEncoder handles encoding of YAML data.

func (*YAMLEncoder) ContentType

func (e *YAMLEncoder) ContentType() string

ContentType returns the content type for YAML data.

func (*YAMLEncoder) Encode

func (e *YAMLEncoder) Encode(v any) (io.Reader, error)

Encode marshals the provided value into YAML format.

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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