requests

package module
v0.6.5 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 37 Imported by: 1

README

requests

Go Version License

A fluent HTTP client library for Go with middleware, retries, proxy and redirect controls, caller-owned streaming, ordered-header intent, optional client profiles, and JSON/XML/YAML helpers.

Features

  • Fluent request builder: Chain path params, query params, headers, cookies, auth, body encoding, and per-request retry settings.
  • Validated construction: Build clients with New(...); malformed options return errors before any request is sent.
  • Retry-aware delivery: Combine retry counts, backoff strategies, and Retry-After handling without wrapping net/http yourself.
  • Transport controls: Configure TLS, mTLS, HTTP/2, redirect policies, proxies, bypass rules, resolver/dialer hooks, and connection pooling.
  • Ordered headers: Express header order as request intent with orderedobject, while preserving net/http header semantics.
  • Optional profiles: Apply browser-like headers, TLS ClientHello fingerprints, or HTTP/3 through separate extension modules.
  • net/http adapters: Use configured requests clients as *http.Client or http.RoundTripper in other SDKs.
  • Response helpers: Decode JSON, XML, or YAML, check status helpers, inspect diagnostics, iterate buffered response lines, or save to disk.
  • Composable middleware: Attach header, cookie, or cache middleware at the client or request level.

Installation

go get github.com/kaptinlin/requests

Requires Go 1.26.4.

Optional extension modules:

go get github.com/kaptinlin/requests/browser
go get github.com/kaptinlin/requests/fingerprint
go get github.com/kaptinlin/requests/http3

Quick Start

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/kaptinlin/requests"
)

type Post struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

func main() {
	client, err := requests.New(
		requests.WithBaseURL("https://api.example.com"),
		requests.WithTimeout(10*time.Second),
	)
	if err != nil {
		log.Fatal(err)
	}

	resp, err := client.Get("/posts/{id}").PathParam("id", "1").Send(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Close()

	var post Post
	if err := resp.DecodeJSON(&post); err != nil {
		log.Fatal(err)
	}

	fmt.Println(post.ID, post.Title)
}

Client Construction

Functional Options
client, err := requests.New(
	requests.WithBaseURL("https://api.example.com"),
	requests.WithTimeout(30*time.Second),
	requests.WithBearerAuth("token"),
	requests.WithRetry(requests.RetryPolicy{Max: 3}),
)
if err != nil {
	log.Fatal(err)
}
Optional profiles

Browser-like defaults:

import (
	"github.com/kaptinlin/requests"
	"github.com/kaptinlin/requests/browser"
)

client, err := requests.New(
	requests.WithProfile(browser.Chrome145()),
)
if err != nil {
	log.Fatal(err)
}

Profiles apply client-level defaults. Request-local headers still override profile headers.

TLS fingerprint profile:

import (
	"github.com/kaptinlin/requests"
	"github.com/kaptinlin/requests/fingerprint"
)

client, err := requests.New(
	requests.WithProfile(fingerprint.Chrome()),
)
if err != nil {
	log.Fatal(err)
}

HTTP/3 profile:

import (
	"crypto/tls"

	"github.com/kaptinlin/requests"
	"github.com/kaptinlin/requests/http3"
)

client, err := requests.New(
	requests.WithProfile(http3.Profile(http3.WithTLSConfig(&tls.Config{
		MinVersion: tls.VersionTLS13,
	}))),
)
if err != nil {
	log.Fatal(err)
}

Optional profile packages keep heavier dependencies out of the core module:

  • github.com/kaptinlin/requests/browser applies browser-like headers, ordered header metadata, and HTTP/2 preference.
  • github.com/kaptinlin/requests/fingerprint applies uTLS ClientHello fingerprints.
  • github.com/kaptinlin/requests/http3 applies a QUIC HTTP/3 transport.
Transport Options
client, err := requests.New(
	requests.WithBaseURL("https://api.example.com"),
	requests.WithTimeout(30*time.Second),
	requests.WithHTTP2(),
	requests.WithTLSServerName("api.example.com"),
	requests.WithDialTimeout(5*time.Second),
	requests.WithTLSHandshakeTimeout(5*time.Second),
	requests.WithResponseHeaderTimeout(10*time.Second),
	requests.WithMaxIdleConnsPerHost(10),
)
if err != nil {
	log.Fatal(err)
}

Making Requests

Ordered headers
import "github.com/kaptinlin/orderedobject"

headers := orderedobject.NewObject[[]string]().
	Set("Accept", []string{"application/json"}).
	Set("User-Agent", []string{"requests-example/1.0"})

resp, err := client.Get("/articles").
	OrderedHeaders(headers).
	Send(context.Background())

Default net/http transports preserve header semantics. Transports that explicitly read requests.OrderedHeaders(req) can use the metadata for wire-order delivery.

JSON request body
resp, err := client.Post("/articles").
	Header("X-Trace-ID", "trace-123").
	JSON(map[string]any{"title": "hello"}).
	Send(context.Background())
Path and query parameters
resp, err := client.Get("/articles/{id}").
	PathParam("id", "42").
	Query("include", "comments").
	Send(context.Background())

Repeated query keys are preserved:

resp, err := client.Get("/search").
	Query("tag", "go").
	Query("tag", "http").
	Send(context.Background())

For non-standard methods, use the method-first request entry:

resp, err := client.Request("PROPFIND", "/files/{id}").
	PathParam("id", "report").
	Send(context.Background())
Forms and files
file, err := os.Open("avatar.png")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

resp, err := client.Post("/upload").
	FormField("user", "alice").
	File("avatar", "avatar.png", file).
	Send(context.Background())

For larger multipart bodies, use the streaming multipart builder:

body := requests.NewMultipart().
	Field("user", "alice").
	File("avatar", "avatar.png", file)

resp, err := client.Post("/upload").
	Multipart(body).
	Send(context.Background())

Use Replayable(maxBytes) when a multipart request must be replayable for retries:

body := requests.NewMultipart().
	Field("user", "alice").
	FileString("note", "note.txt", "hello").
	Replayable(1 << 20)

Retries and Delivery

Client-level retries
client, err := requests.New(
	requests.WithBaseURL("https://api.example.com"),
	requests.WithRetry(requests.RetryPolicy{
		Max: 3,
		Backoff: requests.JitterBackoffStrategy(
			requests.ExponentialBackoffStrategy(250*time.Millisecond, 2, 5*time.Second),
			0.2,
		),
	}),
)
if err != nil {
	log.Fatal(err)
}
Request-level overrides
resp, err := client.Get("/jobs/{id}").
	PathParam("id", "job-1").
	Retry(requests.RetryPolicy{
		Max:     5,
		Backoff: requests.LinearBackoffStrategy(500 * time.Millisecond),
	}).
	Send(context.Background())

Use NoRetry() on a request to disable a positive client default. Replayable request bodies are restored before retry attempts; non-replayable streaming bodies are attempted once.

The retry logic automatically honors Retry-After on 429 and 503 responses.

net/http Integration

Use AsHTTPClient() when another SDK accepts *http.Client:

httpClient := client.AsHTTPClient()
resp, err := httpClient.Get("https://api.example.com/resource")

Use AsTransport() when the caller owns the http.Client:

httpClient := &http.Client{
	Transport: client.AsTransport(),
}

The adapter applies client headers, cookies, auth, and client middleware. It does not run request-builder retries, response buffering, stream responses, or decoding helpers.

UnsafeHTTPClient() exposes the live underlying *http.Client only for advanced integrations that must inspect or mutate raw transport state. Prefer construction options or adapters for ordinary use.

Session and Dialing

client, err := requests.New(
	requests.WithSession(),
	requests.WithHTTP2(),
	requests.WithResolver(net.DefaultResolver),
)
if err != nil {
	log.Fatal(err)
}

WithSession() creates a cookie jar and TLS session cache when missing. WithDialContext and WithLocalAddr are available for custom gateway and network binding setups.

Proxies and Redirects

Proxy configuration
client, err := requests.New(
	requests.WithProxyBypass("http://proxy.internal:8080", "localhost,.svc.cluster.local,10.0.0.0/8"),
)
if err != nil {
	log.Fatal(err)
}

rotating, err := requests.New(
	requests.WithProxies("http://proxy1:8080", "http://proxy2:8080"),
)
if err != nil {
	log.Fatal(err)
}

Proxy URLs support http, https, and socks5 schemes.

Redirect policies
client, err := requests.New(
	requests.WithRedirectPolicy(requests.NewSmartRedirectPolicy(10)),
)

Use NewAllowRedirectPolicy, NewProhibitRedirectPolicy, or NewRedirectSpecifiedDomainPolicy when you need a different redirect strategy.

Responses

Decode structured payloads
var out struct {
	Message string `json:"message"`
}
if err := resp.DecodeJSON(&out); err != nil {
	log.Fatal(err)
}
Save to disk
if err := resp.Save("downloads/report.json"); err != nil {
	log.Fatal(err)
}

resp.Bytes() returns a caller-owned copy of the buffered body. resp.Header() returns a header snapshot; mutate resp.Raw() only when you intentionally need the underlying net/http response.

Iterate line-oriented responses
for line := range resp.Lines() {
	fmt.Printf("%s\n", line)
}
Classify failures
_, err := client.Get("/health").Send(ctx)
switch {
case requests.IsCanceled(err):
	log.Println("caller canceled the request")
case requests.IsTimeout(err):
	log.Println("request hit a deadline")
case requests.IsConnectionError(err):
	log.Println("dial, DNS, or TLS failed")
}

IsCanceled matches context.Canceled only; IsTimeout matches context.DeadlineExceeded and net.Error timeouts. The two are orthogonal so caller-driven cancel can be told apart from a hit deadline. Sentinel errors in errors.go cover non-transport causes (body replay, redirects, decoding, config) — match them with errors.Is.

Inspect diagnostics
fmt.Println(resp.Elapsed())
fmt.Println(resp.Attempts())
fmt.Println(resp.Protocol())
fmt.Println(resp.TLS() != nil)

Streaming

stream, err := client.Get("/events").SendStream(context.Background())
if err != nil {
	log.Fatal(err)
}
defer stream.Close()

for line, err := range stream.Lines() {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("event: %s\n", line)
}

Middleware

headers := http.Header{}
headers.Set("X-Client", "requests")

client, err := requests.New(
	requests.WithMiddleware(
		middlewares.HeaderMiddleware(headers),
		middlewares.CookieMiddleware([]*http.Cookie{{Name: "session", Value: "abc"}}),
	),
)
if err != nil {
	log.Fatal(err)
}

For simple response caching, create a middleware with middlewares.NewCacheMiddleware and a middlewares.Cacher implementation such as middlewares.NewMemoryCache():

cache := middlewares.NewMemoryCache()
defer cache.Close()

mw, err := middlewares.NewCacheMiddleware(cache, time.Minute, logger)
if err != nil {
	log.Fatal(err)
}

client, err := requests.New(requests.WithMiddleware(mw))

The built-in helper caches successful GET responses by scheme, host, path, and query; it is not a full RFC HTTP cache with Cache-Control, Vary, or revalidation semantics.

Documentation

Development

task test            # Run root tests with race detection
task test:all        # Run root and extension tests with race detection
task test:published  # Verify extensions outside go.work after a root release
task lint            # Run root golangci-lint and tidy checks
task lint:all        # Run root and extension linters
task tidy:all        # Tidy root and extension modules
task vuln:all        # Run root and extension vulnerability checks
task verify          # Run deps, fmt, vet, lint, test, and vuln checks for root
task verify:all      # Run full root and extension verification

Contributing

Contributions are welcome. Keep changes focused. Run task test plus task lint for root-only changes, and task test:all plus task lint:all when a change touches extension modules or shared contracts.

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.

Four-object model

The package is built around four public objects:

  • Client owns reusable configuration: base URL, default headers and cookies, auth, retry policy, codecs, logger, and transport settings.
  • RequestBuilder owns one outbound request: method, path, request-local metadata, body, timeout, retries, and middleware.
  • Response exposes the buffered result of one Send call.
  • StreamResponse exposes the unbuffered result of one SendStream call.

Client defaults are formed during New or Clone. State that is reused across requests belongs on Client; state for one request belongs on RequestBuilder.

Quick start

client, err := requests.New(
    requests.WithBaseURL("https://api.example.com"),
    requests.WithTimeout(30*time.Second),
)
if err != nil {
    return err
}

resp, err := client.Get("/users/{id}").
    PathParam("id", "1").
    Send(ctx)
if err != nil {
    return err
}
defer resp.Close()

var user User
if err := resp.DecodeJSON(&user); err != nil {
    return err
}

Construction

Use New with functional options. Construction validates option input and returns an error instead of building a partially configured client.

Body lifecycle

Request body setters fall into two groups:

Errors

Runtime failures are returned as errors; the package does not panic and does not expose Must-style APIs. Use errors.Is with the sentinels declared in errors.go to detect specific causes, and the helpers IsTimeout, IsCanceled, and IsConnectionError to classify transport-level failures.

Extensions

Optional protocol and identity behavior lives in extension modules so the core does not pull their dependencies:

  • github.com/kaptinlin/requests/browser — browser-like ordered headers
  • github.com/kaptinlin/requests/fingerprint — uTLS ClientHello profiles
  • github.com/kaptinlin/requests/http3 — QUIC HTTP/3 transport

All three plug in through the Profile interface.

Specifications

Contract-level rules live under SPECS/ in the repository. Start with SPECS/00-overview.md.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupportedContentType is returned when a body encoder cannot handle
	// the request's Content-Type, or when a raw body is given a value type
	// other than string, []byte, or io.Reader. Set Content-Type explicitly or
	// use a typed body setter (JSON, XML, YAML, Text, Bytes).
	ErrUnsupportedContentType = errors.New("unsupported content type")

	// ErrUnsupportedDataType is returned when a decoder cannot handle the
	// destination type. Pass a pointer to a struct, map, or slice that the
	// codec can populate.
	ErrUnsupportedDataType = errors.New("unsupported data type")

	// ErrEncodingFailed is returned when an encoder rejects a body value.
	// Wrapped errors carry the codec-specific cause; inspect with errors.As.
	ErrEncodingFailed = errors.New("encoding failed")

	// ErrRequestCreationFailed is returned when http.NewRequestWithContext
	// rejects the resolved method, URL, or body. Almost always indicates a
	// malformed BaseURL + path combination; verify with errors.As to surface
	// the underlying *url.Error.
	ErrRequestCreationFailed = errors.New("failed to create request")

	// ErrRequestBodyNotReplayable is returned when retries are configured but
	// the body is a one-shot io.Reader from [RequestBuilder.Reader]. Switch
	// to a buffered body setter such as JSON, Bytes, Form, or call
	// Multipart.Replayable(maxBytes) to opt in to buffering for multipart.
	ErrRequestBodyNotReplayable = errors.New("request body is not replayable")

	// ErrRequestBodyReadIncomplete is returned when a sized request body
	// (ReadAt+Seek+Size) reports fewer bytes than its declared size. Indicates
	// a truncated source; do not retry until the source is fixed.
	ErrRequestBodyReadIncomplete = errors.New("request body read incomplete")

	// ErrResponseReadFailed is returned when the response body cannot be read
	// in full. Wrapped errors carry the I/O cause.
	ErrResponseReadFailed = errors.New("failed to read response")

	// ErrUnsupportedScheme is returned when a proxy URL uses a scheme other
	// than http, https, or socks5.
	ErrUnsupportedScheme = errors.New("unsupported proxy scheme")

	// ErrNoProxies is returned when a proxy rotation function is given an
	// empty list of proxy URLs.
	ErrNoProxies = errors.New("no proxy URLs provided")

	// ErrUnsupportedFormFieldsType is returned when [RequestBuilder.FormFields]
	// or [RequestBuilder.Form] receives a value that is not a struct, map, or
	// url.Values.
	ErrUnsupportedFormFieldsType = errors.New("unsupported form fields type")

	// ErrNotSupportSaveMethod is returned when [Response.Save] is given a
	// destination it does not understand. Use a string path, *os.File, or
	// io.Writer.
	ErrNotSupportSaveMethod = errors.New("unsupported save type")

	// ErrInvalidTransportType is returned when a TLS or HTTP/2 helper is
	// asked to mutate a transport that is not *http.Transport. Set the
	// transport before applying TLS/HTTP/2 options, or apply the option to a
	// *http.Transport directly.
	ErrInvalidTransportType = errors.New("invalid transport type")

	// ErrResponseNil is returned when transport returned no error and no
	// response. Indicates a transport bug; the request should not be retried
	// blindly.
	ErrResponseNil = errors.New("response is nil")

	// ErrAutoRedirectDisabled is returned by [ProhibitRedirectPolicy] when a
	// 3xx response would normally trigger a follow-up request.
	ErrAutoRedirectDisabled = errors.New("auto redirect disabled")

	// ErrTooManyRedirects is returned when a redirect chain exceeds the
	// configured limit. Wrapped errors include the observed limit.
	ErrTooManyRedirects = errors.New("too many redirects")

	// ErrRedirectNotAllowed is returned by [RedirectSpecifiedDomainPolicy]
	// when the redirect target host is not in the allow-list.
	ErrRedirectNotAllowed = errors.New("redirect not allowed")

	// ErrTestTimeout is reserved for use by the package's own tests. It is
	// not produced by Send.
	ErrTestTimeout = errors.New("test timeout: request took too long")

	// ErrInvalidConfigValue is returned by construction options when a value
	// cannot be applied. Wrapped errors name the offending option.
	ErrInvalidConfigValue = errors.New("invalid config value")
)

Sentinel errors returned by the package. Use errors.Is to match against them. The classification helpers below (IsTimeout, IsCanceled, IsConnectionError) cover the most common transport-level questions without forcing callers to enumerate every cause.

View Source
var DefaultFormEncoder = &FormEncoder{}

DefaultFormEncoder is the default FormEncoder instance.

View Source
var DefaultJSONDecoder = &JSONDecoder{}

DefaultJSONDecoder is the default JSONDecoder instance using the JSON v2 streaming decoder.

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{}

DefaultYAMLDecoder is the default YAMLDecoder instance using the goccy/go-yaml streaming decoder.

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 transport errors, request timeouts, rate limiting, and 5xx status codes.

func ExponentialBackoffStrategy

func ExponentialBackoffStrategy(initialInterval time.Duration, multiplier float64, maxBackoffTime time.Duration) func(int) time.Duration

ExponentialBackoffStrategy increases the delay exponentially with each retry attempt.

func IsCanceled added in v0.6.0

func IsCanceled(err error) bool

IsCanceled reports whether err is or wraps context.Canceled, which indicates the caller cancelled the request before completion. Use this to distinguish caller-initiated cancellation from deadline-driven timeout (see IsTimeout).

func IsConnectionError added in v0.3.13

func IsConnectionError(err error) bool

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

func IsTimeout added in v0.3.13

func IsTimeout(err error) bool

IsTimeout reports whether err is or wraps a deadline-driven failure: context.DeadlineExceeded from a request or per-call timeout, or any net.Error whose Timeout method returns true (for example, dial, TLS-handshake, or response-header timeouts).

IsTimeout intentionally does not match context.Canceled; use IsCanceled for explicit cancellation.

func LinearBackoffStrategy

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 OrderedHeaders added in v0.5.0

func OrderedHeaders(req *http.Request) (*orderedobject.Object[[]string], bool)

OrderedHeaders returns the ordered header metadata attached to req, when present.

Default net/http transports do not guarantee wire-order delivery. This metadata is intended for transports that explicitly support ordered headers.

func RandomProxies added in v0.3.13

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

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

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 // Token is the bearer token value.
}

BearerAuth represents an OAuth 2.0 Bearer token.

func (BearerAuth) Apply

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

Apply adds the Bearer token to the request's Authorization header.

func (BearerAuth) Valid

func (b BearerAuth) Valid() bool

Valid checks if the Bearer token is present.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an HTTP client.

func New added in v0.3.14

func New(opts ...Option) (*Client, error)

New creates a Client with functional options applied. It returns an error when any option cannot be applied.

func (*Client) AsHTTPClient added in v0.5.0

func (c *Client) AsHTTPClient() *http.Client

AsHTTPClient returns a net/http client that applies this client's defaults.

The returned client preserves the underlying timeout, cookie jar, redirect policy, and transport at the time AsHTTPClient is called. Its transport applies client headers, cookies, auth, and client-level middleware. RequestBuilder-only behavior such as retries, response buffering, streaming callbacks, and decoding helpers is not part of the returned client.

func (*Client) AsTransport added in v0.5.0

func (c *Client) AsTransport() http.RoundTripper

AsTransport returns a RoundTripper that applies this client's defaults.

Use it when another library owns the *http.Client and only lets callers replace http.Client.Transport. The returned transport snapshots client headers, cookies, auth, middleware, and the underlying transport at call time.

func (*Client) Clone added in v0.6.5

func (c *Client) Clone(opts ...Option) (*Client, error)

Clone returns a new Client with the current defaults plus opts applied.

func (*Client) Connect added in v0.3.12

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

Connect initiates a CONNECT request.

func (*Client) Delete

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

Delete initiates a DELETE request.

func (*Client) Get

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

Get initiates a GET request.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/kaptinlin/requests"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = fmt.Fprint(w, `{"id":1,"title":"delectus aut autem"}`)
	}))
	defer server.Close()

	type post struct {
		ID    int    `json:"id"`
		Title string `json:"title"`
	}

	client, err := requests.New(
		requests.WithBaseURL(server.URL),
		requests.WithTimeout(5*time.Second),
	)
	if err != nil {
		fmt.Println("client error:", err)
		return
	}

	resp, err := client.Get("/posts/{id}").PathParam("id", "1").Send(context.Background())
	if err != nil {
		fmt.Println("request error:", err)
		return
	}
	defer func() { _ = resp.Close() }()

	var p post
	if err := resp.DecodeJSON(&p); err != nil {
		fmt.Println("decode error:", err)
		return
	}

	fmt.Println(p.ID, p.Title)
}
Output:
1 delectus aut autem

func (*Client) GetBaseURL added in v0.4.0

func (c *Client) GetBaseURL() string

GetBaseURL returns the configured base URL in a thread-safe way.

func (*Client) GetTLSConfig added in v0.6.5

func (c *Client) GetTLSConfig() *tls.Config

GetTLSConfig returns a clone of the configured TLS settings.

func (*Client) Head

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

Head initiates a HEAD request.

func (*Client) NewRequestBuilder

func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder

NewRequestBuilder creates a new RequestBuilder with default settings.

func (*Client) Options

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

Options initiates an OPTIONS request.

func (*Client) Patch

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

Patch initiates a PATCH request.

func (*Client) Post

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

Post initiates a POST request.

func (*Client) Put

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

Put initiates a PUT request.

func (*Client) Request added in v0.6.5

func (c *Client) Request(method, path string) *RequestBuilder

Request initiates a request with method and path.

func (*Client) Trace added in v0.3.12

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

Trace initiates a TRACE request.

func (*Client) UnsafeHTTPClient added in v0.6.5

func (c *Client) UnsafeHTTPClient() *http.Client

UnsafeHTTPClient returns the underlying HTTP client for advanced integration.

The returned pointer is shared mutable client state. Callers that mutate it must coordinate their own synchronization and should prefer construction options when possible.

type CustomAuth

type CustomAuth struct {
	Header string // Header is the Authorization header value.
}

CustomAuth allows for custom Authorization header values.

func (CustomAuth) Apply

func (c CustomAuth) Apply(req *http.Request)

Apply sets a custom Authorization header value.

func (CustomAuth) Valid

func (c CustomAuth) Valid() bool

Valid checks if the custom Authorization header value is present.

type Decoder

type Decoder interface {
	// Decode decodes data from r into v.
	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 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

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 FilePart added in v0.5.0

type FilePart struct {
	Field       string
	Filename    string
	ContentType string
	Body        io.Reader
}

FilePart describes one multipart file part.

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 {
	DecodeFunc func(r io.Reader, v any) error // DecodeFunc decodes JSON data into a value.
}

JSONDecoder handles decoding of JSON data.

func (*JSONDecoder) Decode

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

Decode decodes JSON data from the reader into the provided value.

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.

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 represents a log level.

const (
	// LevelDebug enables debug logging.
	LevelDebug Level = iota
	// LevelInfo enables info logging.
	LevelInfo
	// LevelWarn enables warning logging.
	LevelWarn
	// LevelError enables error logging.
	LevelError
)

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 wraps a MiddlewareHandlerFunc with additional behavior.

type MiddlewareHandlerFunc

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

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) Boundary added in v0.5.0

func (m *Multipart) Boundary(boundary string) *Multipart

Boundary sets the multipart boundary.

func (*Multipart) Field added in v0.5.0

func (m *Multipart) Field(name, value string) *Multipart

Field adds a form field.

func (*Multipart) File added in v0.5.0

func (m *Multipart) File(field, filename string, r io.Reader) *Multipart

File adds a file part.

func (*Multipart) FileBytes added in v0.5.0

func (m *Multipart) FileBytes(field, filename string, data []byte) *Multipart

FileBytes adds a file part backed by bytes.

func (*Multipart) FileString added in v0.5.0

func (m *Multipart) FileString(field, filename, data string) *Multipart

FileString adds a file part backed by a string.

func (*Multipart) Part added in v0.5.0

func (m *Multipart) Part(part FilePart) *Multipart

Part adds a file part with explicit metadata.

func (*Multipart) Replayable added in v0.5.0

func (m *Multipart) Replayable(maxBytes int64) *Multipart

Replayable buffers the multipart body up to maxBytes so it can be replayed for retries.

type Option added in v0.6.5

type Option func(*Client) error

Option configures a Client during construction.

func WithAccept added in v0.3.14

func WithAccept(accept string) Option

WithAccept sets the default Accept header.

func WithAuth added in v0.3.14

func WithAuth(auth AuthMethod) Option

WithAuth sets the authentication method for the client.

func WithBaseURL added in v0.3.14

func WithBaseURL(baseURL string) Option

WithBaseURL sets the base URL for the client.

func WithBasicAuth added in v0.3.14

func WithBasicAuth(username, password string) Option

WithBasicAuth sets HTTP Basic Authentication credentials.

func WithBearerAuth added in v0.3.14

func WithBearerAuth(token string) Option

WithBearerAuth sets a Bearer token for authentication.

func WithCertificates added in v0.3.14

func WithCertificates(certs ...tls.Certificate) Option

WithCertificates sets TLS client certificates.

func WithClientCertificate added in v0.4.0

func WithClientCertificate(certFile, keyFile string) Option

WithClientCertificate loads and sets a client certificate and key from file paths.

func WithContentType added in v0.3.14

func WithContentType(contentType string) Option

WithContentType sets the default Content-Type header.

func WithCookieJar added in v0.3.14

func WithCookieJar(jar *cookiejar.Jar) Option

WithCookieJar sets the cookie jar for the client.

func WithCookies added in v0.3.14

func WithCookies(cookies map[string]string) Option

WithCookies sets default cookies on the client.

func WithDialContext added in v0.5.0

func WithDialContext(dial func(context.Context, string, string) (net.Conn, error)) Option

WithDialContext sets the dial function on the underlying transport.

func WithDialTimeout added in v0.3.14

func WithDialTimeout(d time.Duration) Option

WithDialTimeout sets the TCP connection timeout on the underlying transport.

func WithHTTP2 added in v0.5.0

func WithHTTP2() Option

WithHTTP2 enables HTTP/2 transport support.

func WithHTTPClient added in v0.3.14

func WithHTTPClient(httpClient *http.Client) Option

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

WithHeader sets a default header on the client.

func WithHeaders added in v0.3.14

func WithHeaders(headers *http.Header) Option

WithHeaders sets all default headers on the client.

func WithIdleConnTimeout added in v0.3.14

func WithIdleConnTimeout(d time.Duration) Option

WithIdleConnTimeout sets how long idle connections remain in the pool.

func WithInsecureSkipVerify added in v0.3.14

func WithInsecureSkipVerify() Option

WithInsecureSkipVerify configures the client to skip TLS certificate verification.

func WithJSONDecoder added in v0.6.5

func WithJSONDecoder(decoder Decoder) Option

WithJSONDecoder sets the JSON decoder.

func WithJSONEncoder added in v0.6.5

func WithJSONEncoder(encoder Encoder) Option

WithJSONEncoder sets the JSON encoder.

func WithLocalAddr added in v0.5.0

func WithLocalAddr(addr net.Addr) Option

WithLocalAddr sets the local address used by the default transport dialer.

func WithLogger added in v0.3.14

func WithLogger(logger Logger) Option

WithLogger sets the logger for the client.

func WithMaxConnsPerHost added in v0.3.14

func WithMaxConnsPerHost(n int) Option

WithMaxConnsPerHost sets the maximum total number of connections per host.

func WithMaxIdleConns added in v0.3.14

func WithMaxIdleConns(n int) Option

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

func WithMaxIdleConnsPerHost added in v0.3.14

func WithMaxIdleConnsPerHost(n int) Option

WithMaxIdleConnsPerHost sets the maximum number of idle connections per host.

func WithMiddleware added in v0.3.14

func WithMiddleware(middlewares ...Middleware) Option

WithMiddleware adds middleware to the client.

func WithOrderedHeaders added in v0.5.0

func WithOrderedHeaders(headers *orderedobject.Object[[]string]) Option

WithOrderedHeaders sets ordered default headers on the client.

func WithProfile added in v0.5.0

func WithProfile(profile Profile) Option

WithProfile applies a coherent client identity profile.

func WithProxies added in v0.6.5

func WithProxies(proxyURLs ...string) Option

WithProxies sets multiple proxies with round-robin rotation.

func WithProxy added in v0.3.14

func WithProxy(proxyURL string) Option

WithProxy sets the proxy URL for the client.

func WithProxyBypass added in v0.6.5

func WithProxyBypass(proxyURL, bypass string) Option

WithProxyBypass sets a proxy URL with a NO_PROXY-style bypass list.

func WithProxyFromEnv added in v0.6.5

func WithProxyFromEnv() Option

WithProxyFromEnv uses proxy settings from HTTP_PROXY, HTTPS_PROXY, and NO_PROXY.

func WithProxySelector added in v0.6.5

func WithProxySelector(selector func(*http.Request) (*url.URL, error)) Option

WithProxySelector sets a custom proxy selection function.

func WithRedirectPolicy added in v0.3.14

func WithRedirectPolicy(policies ...RedirectPolicy) Option

WithRedirectPolicy sets the redirect policy for the client.

func WithReferer added in v0.3.14

func WithReferer(referer string) Option

WithReferer sets the default Referer header.

func WithResolver added in v0.5.0

func WithResolver(resolver *net.Resolver) Option

WithResolver sets the resolver used by the default transport dialer.

func WithResponseHeaderTimeout added in v0.3.14

func WithResponseHeaderTimeout(d time.Duration) Option

WithResponseHeaderTimeout sets the time to wait for response headers.

func WithRetry added in v0.6.5

func WithRetry(policy RetryPolicy) Option

WithRetry sets the default retry policy.

func WithRootCertificate added in v0.3.14

func WithRootCertificate(pemFilePath string) Option

WithRootCertificate sets the root certificate from a PEM file path.

func WithRootCertificateFromString added in v0.3.14

func WithRootCertificateFromString(pemCerts string) Option

WithRootCertificateFromString sets the root certificate from a PEM string.

func WithSession added in v0.5.0

func WithSession() Option

WithSession enables cookie and TLS session reuse.

func WithTLSConfig added in v0.3.14

func WithTLSConfig(config *tls.Config) Option

WithTLSConfig sets the TLS configuration for the client.

func WithTLSHandshakeTimeout added in v0.3.14

func WithTLSHandshakeTimeout(d time.Duration) Option

WithTLSHandshakeTimeout sets the TLS handshake timeout on the underlying transport.

func WithTLSServerName added in v0.4.0

func WithTLSServerName(serverName string) Option

WithTLSServerName sets the TLS server name (SNI).

func WithTimeout added in v0.3.14

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the default timeout for the client.

func WithTransport added in v0.3.14

func WithTransport(transport http.RoundTripper) Option

WithTransport sets the HTTP transport for the client.

func WithUserAgent added in v0.3.14

func WithUserAgent(userAgent string) Option

WithUserAgent sets the default User-Agent header.

func WithXMLDecoder added in v0.6.5

func WithXMLDecoder(decoder Decoder) Option

WithXMLDecoder sets the XML decoder.

func WithXMLEncoder added in v0.6.5

func WithXMLEncoder(encoder Encoder) Option

WithXMLEncoder sets the XML encoder.

func WithYAMLDecoder added in v0.6.5

func WithYAMLDecoder(decoder Decoder) Option

WithYAMLDecoder sets the YAML decoder.

func WithYAMLEncoder added in v0.6.5

func WithYAMLEncoder(encoder Encoder) Option

WithYAMLEncoder sets the YAML encoder.

func WithoutProxy added in v0.6.5

func WithoutProxy() Option

WithoutProxy clears any configured proxy.

func WithoutRetry added in v0.6.5

func WithoutRetry() Option

WithoutRetry disables retry attempts.

type Profile added in v0.5.0

type Profile interface {
	Name() string
	Options() []Option
}

Profile contributes coherent client identity options during construction.

type ProhibitRedirectPolicy added in v0.2.3

type ProhibitRedirectPolicy struct {
}

ProhibitRedirectPolicy is a redirect policy that does not allow any redirects.

func NewProhibitRedirectPolicy added in v0.2.3

func NewProhibitRedirectPolicy() *ProhibitRedirectPolicy

NewProhibitRedirectPolicy creates a new ProhibitRedirectPolicy that prevents any redirects.

func (*ProhibitRedirectPolicy) Apply added in v0.2.3

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

Apply rejects all redirects by returning ErrAutoRedirectDisabled.

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.

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) Bytes added in v0.6.5

func (b *RequestBuilder) Bytes(v []byte) *RequestBuilder

Bytes sets the request body as raw bytes without changing Content-Type. The body is buffered and is safe to replay for retries.

func (*RequestBuilder) Clone added in v0.3.13

func (b *RequestBuilder) Clone() *RequestBuilder

Clone creates a deep copy of the RequestBuilder. The clone shares the same client reference (shallow copy) but has independent copies of headers, cookies, queries, pathParams, and formFields (deep copy). This means configuration changes to the client will affect both the original and clone.

Body data, multipart bodies, form files, middlewares, and retry config are not copied as they are not safe to share or clone. Set these on the cloned builder if needed.

func (*RequestBuilder) ContentType

func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder

ContentType sets the Content-Type header for the request.

func (*RequestBuilder) Cookie

func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder

Cookie adds a cookie to the request.

func (*RequestBuilder) Cookies

func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder

Cookies adds cookies from a map.

func (*RequestBuilder) DelCookie

func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder

DelCookie removes one or more cookies from the request.

func (*RequestBuilder) DelFile

func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder

DelFile removes one or more files from the request.

func (*RequestBuilder) DelFormField

func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder

DelFormField removes one or more form fields.

func (*RequestBuilder) DelHeader

func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder

DelHeader removes one or more headers from the request.

func (*RequestBuilder) DelPathParam

func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder

DelPathParam removes one or more path params fields from the RequestBuilder instance.

func (*RequestBuilder) DelQuery

func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder

DelQuery removes one or more query parameters from the request.

func (*RequestBuilder) File

func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder

File adds a file to the request. The resulting multipart body is streamed once; use Multipart.Replayable with RequestBuilder.Multipart when retries must resend the body.

func (*RequestBuilder) Files

func (b *RequestBuilder) Files(files ...*File) *RequestBuilder

Files sets multiple files at once. The resulting multipart body is streamed once; use Multipart.Replayable with RequestBuilder.Multipart when retries must resend the body.

func (*RequestBuilder) Form

func (b *RequestBuilder) Form(v any) *RequestBuilder

Form sets form fields and files for the request from a struct, map, or url.Values. The resulting body is buffered and is safe to replay for retries.

func (*RequestBuilder) FormField

func (b *RequestBuilder) FormField(key, val string) *RequestBuilder

FormField adds or updates a form field. Without files, the resulting form body is buffered and safe to replay for retries.

func (*RequestBuilder) FormFields

func (b *RequestBuilder) FormFields(fields any) *RequestBuilder

FormFields sets multiple form fields at once. The resulting body is buffered and is safe to replay for retries.

func (*RequestBuilder) Header

func (b *RequestBuilder) Header(key, value string) *RequestBuilder

Header sets (or replaces) a header in the request.

func (*RequestBuilder) Headers

func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder

Headers set headers to the request.

func (*RequestBuilder) JSON added in v0.6.5

func (b *RequestBuilder) JSON(v any) *RequestBuilder

JSON sets the request body as JSON and Content-Type to application/json. The encoded body is buffered and is safe to replay for retries.

func (*RequestBuilder) Method

func (b *RequestBuilder) Method(method string) *RequestBuilder

Method sets the HTTP method for the request.

func (*RequestBuilder) Multipart added in v0.5.0

func (b *RequestBuilder) Multipart(m *Multipart) *RequestBuilder

Multipart sets a multipart/form-data body built by Multipart.

By default the body is streamed once via an io.Pipe and is not replayable; a retry that needs to resend the body returns ErrRequestBodyNotReplayable. Call m.Replayable(maxBytes) before passing the builder if retries must resend the body.

func (*RequestBuilder) NoRetry added in v0.6.5

func (b *RequestBuilder) NoRetry() *RequestBuilder

NoRetry disables retries for this request.

func (*RequestBuilder) OrderedHeaders added in v0.5.0

func (b *RequestBuilder) OrderedHeaders(headers *orderedobject.Object[[]string]) *RequestBuilder

OrderedHeaders sets ordered headers for the request.

func (*RequestBuilder) Path

func (b *RequestBuilder) Path(path string) *RequestBuilder

Path sets the URL path for the request.

func (*RequestBuilder) PathParam

func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder

PathParam sets a single path param field and its value in the RequestBuilder instance.

func (*RequestBuilder) PathParams

func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder

PathParams sets multiple path params fields and their values at one go in the RequestBuilder instance.

func (*RequestBuilder) Queries

func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder

Queries adds query parameters to the request.

func (*RequestBuilder) QueriesStruct

func (b *RequestBuilder) QueriesStruct(queryStruct any) *RequestBuilder

QueriesStruct adds query parameters to the request based on a struct tagged with url tags.

func (*RequestBuilder) Query

func (b *RequestBuilder) Query(key, value string) *RequestBuilder

Query adds a single query parameter to the request.

func (*RequestBuilder) Reader added in v0.6.5

func (b *RequestBuilder) Reader(r io.Reader, contentType string) *RequestBuilder

Reader sets a one-shot raw request body and optional Content-Type. The body is not replayable unless r itself is seekable and sized.

func (*RequestBuilder) Referer

func (b *RequestBuilder) Referer(referer string) *RequestBuilder

Referer sets the Referer header for the request.

func (*RequestBuilder) Retry added in v0.6.5

func (b *RequestBuilder) Retry(policy RetryPolicy) *RequestBuilder

Retry sets the request-local retry policy, replacing the client policy.

func (*RequestBuilder) Send

func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)

Send executes the HTTP request.

Send takes a snapshot of the client at call time; later mutations on the client do not affect this in-flight request.

Cancellation: ctx propagates through dial, TLS handshake, request header read, body read, retry backoff, and stream callbacks. When ctx is canceled before the response arrives, Send returns ctx.Err() and any partial response is closed internally. When ctx is canceled after the response is returned, the caller is still responsible for calling Response.Close to release the underlying connection.

Retries: if the request body cannot be replayed, retries that would need to resend the body return ErrRequestBodyNotReplayable instead of silently re-sending or silently skipping.

func (*RequestBuilder) SendStream added in v0.6.5

func (b *RequestBuilder) SendStream(ctx context.Context) (*StreamResponse, error)

SendStream sends the request and returns an unbuffered streaming response.

func (*RequestBuilder) Text added in v0.6.5

func (b *RequestBuilder) Text(v string) *RequestBuilder

Text sets the request body as plain text and Content-Type to text/plain. The body is buffered and is safe to replay for retries.

func (*RequestBuilder) Timeout

func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder

Timeout sets the request timeout.

func (*RequestBuilder) UserAgent

func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder

UserAgent sets the User-Agent header for the request.

func (*RequestBuilder) XML added in v0.6.5

func (b *RequestBuilder) XML(v any) *RequestBuilder

XML sets the request body as XML and Content-Type to application/xml. The encoded body is buffered and is safe to replay for retries.

func (*RequestBuilder) YAML added in v0.6.5

func (b *RequestBuilder) YAML(v any) *RequestBuilder

YAML sets the request body as YAML and Content-Type to application/yaml. The encoded body is buffered and is safe to replay for retries.

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response represents an HTTP response.

func (*Response) Attempts added in v0.5.0

func (r *Response) Attempts() int

Attempts returns the total number of transport attempts, including the first request.

func (*Response) Bytes added in v0.6.5

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

Bytes returns the response body as a caller-owned 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) Decode added in v0.6.5

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

Decode decodes the response body based on its content type.

func (*Response) DecodeJSON added in v0.6.5

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

DecodeJSON decodes the response body as JSON.

func (*Response) DecodeXML added in v0.6.5

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

DecodeXML decodes the response body as XML.

func (*Response) DecodeYAML added in v0.6.5

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

DecodeYAML decodes the response body as YAML.

func (*Response) Elapsed added in v0.5.0

func (r *Response) Elapsed() time.Duration

Elapsed returns the duration from request dispatch through response setup.

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 over the buffered response body lines.

func (*Response) Location

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

Location returns the URL redirected address.

func (*Response) Protocol added in v0.5.0

func (r *Response) Protocol() string

Protocol returns the response protocol, such as "HTTP/1.1" or "HTTP/2.0".

func (*Response) Raw added in v0.6.5

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

Raw returns the underlying HTTP response for callers that need net/http details.

func (*Response) Save

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

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

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) TLS added in v0.5.0

func (r *Response) TLS() *tls.ConnectionState

TLS returns a copy of the response TLS connection state, if any.

func (*Response) URL

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

URL returns the request URL that elicited the response.

type RetryIfFunc

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

RetryIfFunc defines the function signature for retry conditions.

type RetryPolicy added in v0.6.5

type RetryPolicy struct {
	// Max is the number of retry attempts after the first delivery attempt.
	Max int
	// Backoff returns the delay before the next retry.
	Backoff BackoffStrategy
	// ShouldRetry decides whether an HTTP response should be retried.
	ShouldRetry RetryIfFunc
	// IgnoreRetryAfter makes Backoff authoritative even when Retry-After is present.
	IgnoreRetryAfter bool
}

RetryPolicy describes retry delivery as one value.

func DefaultRetryPolicy added in v0.6.5

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default retry behavior with retries disabled.

type SmartRedirectPolicy added in v0.3.13

type SmartRedirectPolicy struct {
	// contains filtered or unexported fields
}

SmartRedirectPolicy is a redirect policy that downgrades POST to GET on 301/302/303 redirects and strips sensitive headers on cross-host or scheme-downgrade redirects.

func NewSmartRedirectPolicy added in v0.3.13

func NewSmartRedirectPolicy(maxRedirects int) *SmartRedirectPolicy

NewSmartRedirectPolicy creates a new SmartRedirectPolicy with the given redirect limit.

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 StreamResponse added in v0.6.5

type StreamResponse struct {
	// contains filtered or unexported fields
}

StreamResponse is an unbuffered HTTP response whose body is owned by the caller.

func (*StreamResponse) Attempts added in v0.6.5

func (r *StreamResponse) Attempts() int

Attempts returns the total number of transport attempts, including the first request.

func (*StreamResponse) Body added in v0.6.5

func (r *StreamResponse) Body() io.ReadCloser

Body returns the live response body. The caller must close the response.

func (*StreamResponse) Close added in v0.6.5

func (r *StreamResponse) Close() error

Close closes the response body and releases the request context.

func (*StreamResponse) Elapsed added in v0.6.5

func (r *StreamResponse) Elapsed() time.Duration

Elapsed returns the duration from request dispatch through response setup.

func (*StreamResponse) Header added in v0.6.5

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

Header returns the response headers.

func (*StreamResponse) Lines added in v0.6.5

func (r *StreamResponse) Lines() iter.Seq2[[]byte, error]

Lines returns an iterator over streamed response body lines.

func (*StreamResponse) Raw added in v0.6.5

func (r *StreamResponse) Raw() *http.Response

Raw returns the underlying HTTP response for callers that need net/http details.

func (*StreamResponse) Status added in v0.6.5

func (r *StreamResponse) Status() string

Status returns the status string of the response.

func (*StreamResponse) StatusCode added in v0.6.5

func (r *StreamResponse) StatusCode() int

StatusCode returns the HTTP status code of the response.

func (*StreamResponse) URL added in v0.6.5

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

URL returns the request URL that elicited the response.

type XMLDecoder

type XMLDecoder struct {
	UnmarshalFunc func(data []byte, v any) error // UnmarshalFunc unmarshals XML data into a value.
}

XMLDecoder handles decoding of XML data.

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) // 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.

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 {
	DecodeFunc func(r io.Reader, v any) error // DecodeFunc decodes YAML data into a value.
}

YAMLDecoder handles decoding of YAML data.

func (*YAMLDecoder) Decode

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

Decode decodes YAML data from the reader into the provided value.

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.

func (*YAMLEncoder) Encode

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

Encode marshals the provided value into YAML format.

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.

Jump to

Keyboard shortcuts

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