httpclient

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 14 Imported by: 3 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

HTTP Client

Existing clients retain their defaults: a 30-second timeout, certificate verification, TLS 1.2 minimum, HTTP/2 negotiation, up to ten redirects, and fully buffered response bodies without a size limit.

Custom Transports

WithTransport(*http.Transport) clones a caller-configured transport. This lets a scanner connect to a specific IP and port while using a separate URL hostname for HTTP Host and TLS SNI. The clone owns its connections; call client.CloseIdleConnections() when finished. Do not modify the source transport's configuration concurrently with client construction.

The supplied transport controls dialing, TLS (including verification), HTTP/2, and connection settings. WithTLSVerify only affects the default transport. Explicit HTTP/SOCKS proxy options still apply to the clone; SOCKS replaces its custom dialer. Do not enable proxies when direct IP-pinned dialing is required.

transport := &http.Transport{
    DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
        return (&net.Dialer{}).DialContext(ctx, network, "192.0.2.10:443")
    },
    DisableKeepAlives: true,
}
client := httpclient.New(
    httpclient.WithTransport(transport),
    httpclient.WithTimeout(5*time.Second),
    httpclient.WithDefaultHeaders(map[string]string{"User-Agent": selectedUserAgent}),
)
defer client.CloseIdleConnections()

response, err := client.Head(ctx, "https://app.example.com/")

Callers can supply transport.TLSClientConfig for explicit SNI, self-signed certificates, or discovery-only legacy TLS requirements. These settings are not enabled globally or by default.

The existing request methods retain their normal timeout, redirect, and response buffering behavior. Scanner-specific request sequences and service classification belong in the calling application, not this package.

Bounded Bodies

WithMaxResponseBodyBytes(n) optionally limits buffered bodies returned by the existing request methods. A positive limit returns at most n bytes and ErrResponseBodyTooLarge when exceeded; the returned response retains status and headers. Use errors.Is(err, httpclient.ErrResponseBodyTooLarge) to distinguish this condition. JSON convenience methods stop on this error rather than decoding truncated JSON. Zero or negative limits preserve unlimited buffering. IsAlive still evaluates the returned status when the only error is an oversized body; 404 and 502 remain unavailable, and other request errors still return false.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrResponseBodyTooLarge = errors.New("HTTP response body exceeds configured limit")

ErrResponseBodyTooLarge indicates that a configured response body limit was exceeded.

Functions

func DelayWithJitter

func DelayWithJitter(baseDelay, jitter time.Duration) time.Duration

DelayWithJitter returns a duration with random jitter applied. The result is between baseDelay and baseDelay + jitter.

func Sleep

func Sleep(baseDelay, jitter time.Duration)

Sleep pauses execution for the base delay plus random jitter.

Types

type Client

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

Client wraps http.Client with Method-specific defaults and helpers.

func New

func New(opts ...Option) *Client

New creates a new HTTP client with the given options.

func (*Client) CloseIdleConnections added in v0.2.0

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes this client's idle connections without interrupting active requests. The transport supplied to WithTransport is not affected.

func (*Client) Do

func (c *Client) Do(req *http.Request) (*Response, error)

Do executes an HTTP request, handling redirects manually.

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) (*Response, error)

Get performs an HTTP GET request.

func (*Client) GetJSON

func (c *Client) GetJSON(ctx context.Context, url string, dest any) (*Response, error)

GetJSON performs a GET request and unmarshals the JSON response into dest.

func (*Client) GetWithHeaders

func (c *Client) GetWithHeaders(ctx context.Context, url string, headers map[string]string) (*Response, error)

GetWithHeaders performs an HTTP GET request with custom headers.

func (*Client) Head

func (c *Client) Head(ctx context.Context, url string) (*Response, error)

Head performs an HTTP HEAD request.

func (*Client) HeadWithHeaders

func (c *Client) HeadWithHeaders(ctx context.Context, url string, headers map[string]string) (*Response, error)

HeadWithHeaders performs an HTTP HEAD request with custom headers.

func (*Client) IsAlive

func (c *Client) IsAlive(ctx context.Context, url string) bool

IsAlive checks if a URL responds with a non-404/502 status code.

func (*Client) Post

func (c *Client) Post(ctx context.Context, url string, body any) (*Response, error)

Post performs an HTTP POST request with a JSON body.

func (*Client) PostForm

func (c *Client) PostForm(ctx context.Context, requestURL string, values url.Values) (*Response, error)

PostForm performs an HTTP POST request with form-encoded body.

func (*Client) PostFormWithHeaders

func (c *Client) PostFormWithHeaders(ctx context.Context, requestURL string, values url.Values, headers map[string]string) (*Response, error)

PostFormWithHeaders performs an HTTP POST request with form-encoded body and custom headers.

func (*Client) PostJSON

func (c *Client) PostJSON(ctx context.Context, url string, body any, dest any) (*Response, error)

PostJSON performs a POST request with a JSON body and unmarshals the response into dest.

func (*Client) PostWithHeaders

func (c *Client) PostWithHeaders(ctx context.Context, url string, body any, headers map[string]string) (*Response, error)

PostWithHeaders performs an HTTP POST request with a JSON body and custom headers.

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, requestURL string, body io.Reader, headers map[string]string) (*Response, error)

Request performs an HTTP request with an arbitrary method, body, and headers.

type Option

type Option func(*Options)

Option is a functional option for configuring the HTTP client.

func WithBlockCrossDomainRedirects

func WithBlockCrossDomainRedirects() Option

WithBlockCrossDomainRedirects blocks redirects that change the host.

func WithDefaultHeaders

func WithDefaultHeaders(headers map[string]string) Option

WithDefaultHeaders sets headers that are applied to every request.

func WithHTTPProxy added in v0.1.0

func WithHTTPProxy(proxyURL string) Option

WithHTTPProxy sets an HTTP/HTTPS proxy URL for all requests. The proxyURL should be in the format: http://[user:pass@]host:port

func WithMaxRedirects

func WithMaxRedirects(n int) Option

WithMaxRedirects sets the maximum number of redirects to follow. Set to 0 to disable redirects. Default is 10.

func WithMaxResponseBodyBytes added in v0.2.0

func WithMaxResponseBodyBytes(n int64) Option

WithMaxResponseBodyBytes limits buffered response bodies. Non-positive values retain the default unlimited buffering. Oversized responses return the bounded body and ErrResponseBodyTooLarge.

func WithRedirectTracking

func WithRedirectTracking() Option

WithRedirectTracking enables tracking of the full redirect chain in responses.

func WithSOCKSProxy added in v0.1.0

func WithSOCKSProxy(proxyURL string) Option

WithSOCKSProxy sets a SOCKS5 proxy URL for all requests. The proxyURL should be in the format: socks5://[user:pass@]host:port

func WithTLSVerify

func WithTLSVerify(verify bool) Option

WithTLSVerify controls certificate verification for the default transport. WithTransport takes precedence over this option.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP request timeout.

func WithTransport added in v0.2.0

func WithTransport(transport *http.Transport) Option

WithTransport supplies a transport to clone for this client's exclusive use. Its dialing, TLS, HTTP/2, and connection settings replace the defaults, including WithTLSVerify. Explicit proxy options still apply; SOCKS replaces DialContext. A nil transport selects the default transport. Do not mutate the supplied transport's configuration while New is cloning it.

type Options

type Options struct {
	Timeout                   time.Duration
	VerifyTLS                 bool
	MaxRedirects              int
	TrackRedirects            bool
	BlockCrossDomainRedirects bool
	DefaultHeaders            map[string]string
	HTTPProxy                 string
	SOCKSProxy                string
	Transport                 *http.Transport
	MaxResponseBodyBytes      int64
}

Options configures the HTTP client behavior.

type RedirectHop

type RedirectHop struct {
	URL        string
	StatusCode int
}

RedirectHop records a single redirect in the chain.

type Response

type Response struct {
	StatusCode    int
	Headers       http.Header
	Body          []byte
	RedirectChain []RedirectHop
}

Response wraps an HTTP response with additional metadata.

Jump to

Keyboard shortcuts

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