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
- func New(opts ...Option) *http.Client
- type Option
- func WithAdditionalRetryableMethods(methods ...string) Option
- func WithAdditionalRetryableStatusCodes(codes ...int) Option
- func WithCheckRetry(fn func(req *http.Request, resp *http.Response, err error) bool) Option
- func WithDialContext(fn func(ctx context.Context, network, address string) (net.Conn, error)) Option
- func WithDialKeepAlive(d time.Duration) Option
- func WithDialTimeout(d time.Duration) Option
- func WithDisableCompression() Option
- func WithDisableKeepAlives() Option
- func WithExpectContinueTimeout(d time.Duration) Option
- func WithForceHTTP2(force bool) Option
- func WithIdleConnTimeout(d time.Duration) Option
- func WithMaxConnsPerHost(n int) Option
- func WithMaxIdleConns(n int) Option
- func WithMaxIdleConnsPerHost(n int) Option
- func WithMaxResponseHeaderBytes(n int64) Option
- func WithMaxRetryAfter(d time.Duration) Option
- func WithMaxRetryBodyBytes(n int64) Option
- func WithNoProxy() Option
- func WithNoRedirects() Option
- func WithNoRetries() Option
- func WithProxy(fn func(*http.Request) (*url.URL, error)) Option
- func WithRedirectPolicy(n int) Option
- func WithResolver(r *net.Resolver) Option
- func WithResponseHeaderTimeout(d time.Duration) Option
- func WithRetries(n int) Option
- func WithRetryObserver(fn func(attempt int, req *http.Request, resp *http.Response, err error)) Option
- func WithRetryWait(minWait, maxWait time.Duration) Option
- func WithRetryableMethods(methods ...string) Option
- func WithRetryableStatusCodes(codes ...int) Option
- func WithTLSConfig(cfg *tls.Config) Option
- func WithTLSHandshakeTimeout(d time.Duration) Option
- func WithTimeout(d time.Duration) Option
- func WithTransport(rt http.RoundTripper) Option
- func WithUserAgent(ua string) Option
Constants ¶
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 ¶
Types ¶
type Option ¶
type Option func(*config)
Option configures the HTTP client.
func WithAdditionalRetryableMethods ¶
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 ¶
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 ¶
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 ¶
WithDialKeepAlive sets the TCP keep-alive interval for connections. Default: 30s.
func WithDialTimeout ¶
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 ¶
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 ¶
WithForceHTTP2 controls whether HTTP/2 is attempted when a custom TLS config is set. Default: true.
func WithIdleConnTimeout ¶
WithIdleConnTimeout sets how long idle connections remain in the pool. Default: 90s.
func WithMaxConnsPerHost ¶
WithMaxConnsPerHost sets the maximum total connections per host. 0 means unlimited. Default: 100.
func WithMaxIdleConns ¶
WithMaxIdleConns sets the maximum number of idle connections across all hosts. Default: 20.
func WithMaxIdleConnsPerHost ¶
WithMaxIdleConnsPerHost sets the maximum number of idle connections per host. Default: 20 (stdlib default is 2).
func WithMaxResponseHeaderBytes ¶ added in v0.0.2
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 ¶
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 ¶
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 WithProxy ¶ added in v0.0.2
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 ¶
WithRedirectPolicy sets the maximum number of redirects to follow. Set to 0 to disable redirects. Default: 5.
func WithResolver ¶ added in v0.0.2
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 ¶
WithResponseHeaderTimeout sets the maximum time to wait for response headers after the request is fully written. 0 means no limit. Default: 10s.
func WithRetries ¶
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 ¶
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 ¶
WithRetryableMethods replaces the default retryable HTTP methods. Default: GET, HEAD, OPTIONS.
func WithRetryableStatusCodes ¶
WithRetryableStatusCodes replaces the default retryable status codes. Default: 429, 502, 503, 504.
func WithTLSConfig ¶
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 ¶
WithTLSHandshakeTimeout sets the maximum time for TLS handshakes. Default: 5s.
func WithTimeout ¶
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 ¶
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).