jttp

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2026 License: MIT Imports: 13 Imported by: 0

README

jttp

ci Go Reference

A robust HTTP client for Go with good defaults and tunable behavior.

jttp.New() returns a standard *http.Client with sensible timeouts, connection pooling, and retry logic built in.

Usage

// Use the defaults:
client := jttp.New()
resp, err := client.Get("https://example.com")

// Or tune as needed:
client := jttp.New(
    jttp.WithTimeout(10 * time.Second),
    jttp.WithRetries(5),
    jttp.WithAdditionalRetryableStatusCodes(500),
)

Documentation

Overview

Package jttp provides a robust HTTP client with reasonable defaults and tunable behavior.

The returned *http.Client is fully standard — callers use client.Do, client.Get, etc. Optional retry logic is implemented at the RoundTripper layer with exponential backoff and jitter.

Basic usage:

client := jttp.New() // be sure to reuse this single object across multiple requests!
resp, err := client.Get("https://example.com")

With options:

client := jttp.New(
    jttp.WithTimeout(10 * time.Second),
    jttp.WithRetries(5),
    jttp.WithAdditionalRetryableStatusCodes(500),
)

Index

Constants

View Source
const (
	DefaultTimeout               = 30 * time.Second
	DefaultMaxRedirects          = 5
	DefaultMaxIdleConns          = 20
	DefaultMaxIdleConnsPerHost   = 20
	DefaultMaxConnsPerHost       = 100
	DefaultIdleConnTimeout       = 90 * time.Second
	DefaultTLSHandshakeTimeout   = 5 * time.Second
	DefaultResponseHeaderTimeout = 10 * time.Second
	DefaultDialTimeout           = 5 * time.Second
	DefaultDialKeepAlive         = 30 * time.Second
	DefaultMaxRetries            = 3
	DefaultRetryWaitMin          = 250 * time.Millisecond
	DefaultRetryWaitMax          = 2 * time.Second
	DefaultExpectContinueTimeout = 2 * time.Second
	DefaultMaxRetryBodyBytes     = 4 << 20 // 4 MiB
	DefaultMaxRetryAfter         = 1 * time.Minute
)

Default configuration values. All can be overridden via Option values.

Variables

This section is empty.

Functions

func New

func New(opts ...Option) *http.Client

New creates a new *http.Client with good defaults. All defaults can be overridden via Option values. As with all http.Clients, be sure to use the returned client across the lifetime of multiple requests.

Types

type Option

type Option func(*config)

Option configures the HTTP client.

func WithAdditionalRetryableMethods

func WithAdditionalRetryableMethods(methods ...string) Option

WithAdditionalRetryableMethods adds HTTP methods to the default retryable set without replacing it. For example, to also retry POST and PUT:

jttp.New(jttp.WithAdditionalRetryableMethods("POST", "PUT"))

func WithAdditionalRetryableStatusCodes

func WithAdditionalRetryableStatusCodes(codes ...int) Option

WithAdditionalRetryableStatusCodes adds status codes to the default retryable set without replacing it. For example, to also retry on 500:

jttp.New(jttp.WithAdditionalRetryableStatusCodes(500))

func WithCheckRetry

func WithCheckRetry(fn func(req *http.Request, resp *http.Response, err error) bool) Option

WithCheckRetry provides a custom function to determine if a request should be retried. When set, this overrides the default status-code and error classification logic, but the method check still applies first — only methods in the retryable set are candidates for retry. Return true to retry, false to stop.

func WithDialContext added in v0.0.2

func WithDialContext(fn func(ctx context.Context, network, address string) (net.Conn, error)) Option

WithDialContext provides a custom function for establishing TCP connections. When set, WithDialTimeout, WithDialKeepAlive, and WithResolver are ignored since they configure the default dialer that this replaces. This option is ignored when WithTransport is used.

func WithDialKeepAlive

func WithDialKeepAlive(d time.Duration) Option

WithDialKeepAlive sets the TCP keep-alive interval for connections. Default: 30s.

func WithDialTimeout

func WithDialTimeout(d time.Duration) Option

WithDialTimeout sets the maximum time to establish a TCP connection. Default: 5s (stdlib default is 30s).

func WithDisableCompression

func WithDisableCompression() Option

WithDisableCompression disables transparent gzip decompression. The client will not add Accept-Encoding: gzip and will not decompress responses automatically. This can be useful when Content-Length must match the actual body size.

func WithDisableKeepAlives

func WithDisableKeepAlives() Option

WithDisableKeepAlives disables HTTP keep-alives, making each request use a new connection. Useful for short-lived CLI tools.

func WithExpectContinueTimeout

func WithExpectContinueTimeout(d time.Duration) Option

WithExpectContinueTimeout sets the maximum time to wait for a server's first response headers after fully writing the request headers if the request has an "Expect: 100-continue" header. Default: 2s.

func WithForceHTTP2

func WithForceHTTP2(force bool) Option

WithForceHTTP2 controls whether HTTP/2 is attempted when a custom TLS config is set. Default: true.

func WithIdleConnTimeout

func WithIdleConnTimeout(d time.Duration) Option

WithIdleConnTimeout sets how long idle connections remain in the pool. Default: 90s.

func WithMaxConnsPerHost

func WithMaxConnsPerHost(n int) Option

WithMaxConnsPerHost sets the maximum total connections per host. 0 means unlimited. Default: 100.

func WithMaxIdleConns

func WithMaxIdleConns(n int) Option

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

func WithMaxIdleConnsPerHost

func WithMaxIdleConnsPerHost(n int) Option

WithMaxIdleConnsPerHost sets the maximum number of idle connections per host. Default: 20 (stdlib default is 2).

func WithMaxResponseHeaderBytes added in v0.0.2

func WithMaxResponseHeaderBytes(n int64) Option

WithMaxResponseHeaderBytes sets the maximum number of response bytes that the transport will read looking for the header. 0 means no limit. This option is ignored when WithTransport is used.

func WithMaxRetryAfter

func WithMaxRetryAfter(d time.Duration) Option

WithMaxRetryAfter sets the maximum duration that a server's Retry-After header will be respected. If the server requests a longer delay, it will be capped at this value. Retry-After values are also floored at the minimum retry wait time (see WithRetryWait). Default: 1 minute.

func WithMaxRetryBodyBytes

func WithMaxRetryBodyBytes(n int64) Option

WithMaxRetryBodyBytes sets the maximum request body size (in bytes) that will be buffered into memory for retry support. Bodies larger than this limit cause an error when retries are enabled and the body is not already seekable. Set to 0 for no limit. Default: 4 MiB.

func WithNoProxy added in v0.0.2

func WithNoProxy() Option

WithNoProxy disables proxy support, making all connections direct. This option is ignored when WithTransport is used.

func WithNoRedirects

func WithNoRedirects() Option

WithNoRedirects disables following redirects.

func WithNoRetries

func WithNoRetries() Option

WithNoRetries disables retry logic entirely.

func WithProxy added in v0.0.2

func WithProxy(fn func(*http.Request) (*url.URL, error)) Option

WithProxy sets a custom proxy function for the transport. The default is http.ProxyFromEnvironment. Use WithNoProxy to disable proxy support entirely. This option is ignored when WithTransport is used.

func WithRedirectPolicy

func WithRedirectPolicy(n int) Option

WithRedirectPolicy sets the maximum number of redirects to follow. Set to 0 to disable redirects. Default: 5.

func WithResolver added in v0.0.2

func WithResolver(r *net.Resolver) Option

WithResolver sets a custom DNS resolver on the default dialer. This is useful for directing DNS queries to a specific server (e.g., 1.1.1.1) without replacing the entire dial function. Example:

jttp.New(jttp.WithResolver(&net.Resolver{
    PreferGo: true,
    Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
        return (&net.Dialer{}).DialContext(ctx, "udp", "1.1.1.1:53")
    },
}))

This option is ignored when WithDialContext or WithTransport is used.

func WithResponseHeaderTimeout

func WithResponseHeaderTimeout(d time.Duration) Option

WithResponseHeaderTimeout sets the maximum time to wait for response headers after the request is fully written. 0 means no limit. Default: 10s.

func WithRetries

func WithRetries(n int) Option

WithRetries sets the maximum number of retries. 0 disables retries. Default: 3.

func WithRetryObserver

func WithRetryObserver(fn func(attempt int, req *http.Request, resp *http.Response, err error)) Option

WithRetryObserver registers a callback that is invoked before each retry attempt. The attempt number is 0-indexed (0 = first failed attempt that will be retried). This is not called on the final exhausted attempt — only when a retry will actually follow. This is useful for logging or metrics.

func WithRetryWait

func WithRetryWait(minWait, maxWait time.Duration) Option

WithRetryWait sets the minimum and maximum wait times between retries. Backoff is exponential with full jitter within these bounds. Default: 250ms min, 2s max.

func WithRetryableMethods

func WithRetryableMethods(methods ...string) Option

WithRetryableMethods replaces the default retryable HTTP methods. Default: GET, HEAD, OPTIONS.

func WithRetryableStatusCodes

func WithRetryableStatusCodes(codes ...int) Option

WithRetryableStatusCodes replaces the default retryable status codes. Default: 429, 502, 503, 504.

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) Option

WithTLSConfig sets a custom TLS configuration on the default transport. A minimum TLS version of 1.2 is enforced regardless of the provided config. This option is ignored when WithTransport is used.

func WithTLSHandshakeTimeout

func WithTLSHandshakeTimeout(d time.Duration) Option

WithTLSHandshakeTimeout sets the maximum time for TLS handshakes. Default: 5s.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the overall client timeout (dial + TLS + headers + body). Default: 30s.

func WithTransport

func WithTransport(rt http.RoundTripper) Option

WithTransport provides a custom base RoundTripper, bypassing the default transport construction. Retry logic is still applied on top.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header on requests that don't already have one. By default, no User-Agent override is applied (the stdlib default is used).

Jump to

Keyboard shortcuts

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