http

package
v0.36.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 10 Imported by: 5 modules, 17 packages

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.

Documentation

Overview

Package http provides HTTP client and server constructors tuned for services running on Kubernetes, together with middleware composition and common header name constants.

Clients

NewInternalHTTPClient targets other workloads in the same cluster and NewExternalHTTPClient targets third-party APIs on the public internet. Both are customized with HTTPClientOption values; transport options must be applied before wrapping options such as HTTPClientWithTelemetry:

client := http.NewInternalHTTPClient(
	http.HTTPClientWithMaxConnsPerHost(64),
	http.HTTPClientWithTelemetry(),
)

Create one client per upstream and reuse it for the lifetime of the process.

Servers

NewServer returns a net/http.Server with production timeouts whose handler is wrapped with Middleware values via Compose.

Index

Constants

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedHost      = "X-Forwarded-Host"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXResponseTime       = "X-Response-Time"
	HeaderXPoweredBy          = "X-Powered-By"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderXSessionID          = "X-Session-ID"
	HeaderXTrackingID         = "X-Tracking-ID"
	HeaderXError              = "X-Error"
	HeaderXRuntime            = "X-Runtime"
	HeaderServer              = "Server"
	HeaderTrueClientIP        = "True-Client-Ip"
	HeaderOrigin              = "Origin"
	HeaderXReferer            = "X-Referer"
	HeaderUserAgent           = "User-Agent"

	HeaderCloudflareIPCountry    = "Cf-Ipcountry"
	HeaderCloudflareRay          = "Cf-Ray"
	HeaderCloudflareConnectingIP = "Cf-Connecting-Ip"
	HeaderCloudflareVisitor      = "Cf-Visitor"

	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"

	HeaderTraceParent = "Traceparent"
	HeaderTraceState  = "Tracestate"
)

Canonical names of HTTP request and response headers, including common de-facto, Cloudflare, CORS, security and W3C trace context headers.

View Source
const (
	HeaderValueAuthorizationPrefix = "Bearer "
)

HeaderValueAuthorizationPrefix is the prefix of a bearer token in the Authorization header.

Variables

This section is empty.

Functions

func Compose added in v0.24.0

func Compose(l *zap.Logger, name string, handler http.Handler, middlewares ...Middleware) http.Handler

Compose wraps handler with the given middlewares and returns the result. Middlewares are applied in order, so the last one is the outermost and sees a request first.

func DefaultHTTPTransport deprecated added in v0.11.6

func DefaultHTTPTransport() *http.Transport

DefaultHTTPTransport returns the legacy transport used by NewHTTPClient.

This transport disables connection pooling and leaves MaxIdleConnsPerHost (defaulting to 2), MaxConnsPerHost, IdleConnTimeout and ResponseHeaderTimeout unset.

Deprecated: Use NewHTTPTransport instead.

func DefaultHTTPTransportDialer deprecated added in v0.11.6

func DefaultHTTPTransportDialer() *net.Dialer

DefaultHTTPTransportDialer returns the legacy dialer used by DefaultHTTPTransport.

It uses a 45s dial timeout and keep-alive period. A 45s dial timeout is far too slack for in-cluster traffic, where a slow dial means the endpoint is gone rather than far away, and the loose keep-alive takes minutes to notice a pod that disappeared without a FIN.

Deprecated: Use NewHTTPTransportDialer instead.

func NewExternalHTTPClient added in v0.29.0

func NewExternalHTTPClient(opts ...HTTPClientOption) *http.Client

NewExternalHTTPClient returns a client tuned for third-party HTTPS APIs, using NewHTTPTransport with internal set to false and a 30s timeout. The same reuse rule applies as for NewInternalHTTPClient.

func NewHTTPClient deprecated added in v0.6.0

func NewHTTPClient(opts ...HTTPClientOption) *http.Client

NewHTTPClient returns a client using the legacy transport from DefaultHTTPTransport and a two minute timeout. Compared to the tuned constructors it differs as follows:

setting                 legacy        NewExternalHTTPClient
DisableKeepAlives       true          false
MaxIdleConnsPerHost     2 (default)   16
MaxConnsPerHost         unlimited     32
IdleConnTimeout         unlimited     60s
ResponseHeaderTimeout   unset         10s
dial timeout            45s           5s
Timeout                 2m            30s

The worst of these is DisableKeepAlives: every request pays a fresh handshake and leaves a socket in TIME_WAIT for ~60s, so a few hundred requests per second exhausts the ephemeral port range. The symptom is intermittent dial failures that look like a network fault.

Migrating is not purely mechanical. Callers relying on the two minute timeout for slow endpoints must also raise ResponseHeaderTimeout, which the tuned defaults bound at 10s — otherwise a request that takes 45s to produce its first byte fails even with a generous overall timeout.

Deprecated: Use NewInternalHTTPClient or NewExternalHTTPClient instead.

func NewHTTPTransport added in v0.29.0

func NewHTTPTransport(internal bool) *http.Transport

NewHTTPTransport returns a tuned transport. Each call returns a distinct *http.Transport and therefore a distinct connection pool.

internal selects tuning for another Deployment in the same cluster, reached through a ClusterIP Service with no sidecar or gateway in the path; false targets an API on the public internet.

The two differ because the network in between differs. kube-proxy is an L4 balancer that picks a backend pod once per TCP connection, whereas a public API sits behind an L7 load balancer that routes per request. That single fact drives the protocol choice, the pool width and the timeouts.

                          internal   external
dial timeout              2s         5s
client timeout (caller)   10s        30s
MaxIdleConns              256        64
MaxIdleConnsPerHost       64         16
MaxConnsPerHost           128        32
IdleConnTimeout           30s        60s
ResponseHeaderTimeout     5s         10s
MaxResponseHeaderBytes    1 MiB      64 KiB
HTTP/2                    no         yes
compression               off        on

func NewHTTPTransportDialer added in v0.29.0

func NewHTTPTransportDialer(internal bool) *net.Dialer

NewHTTPTransportDialer returns the dialer used by NewHTTPTransport.

internal selects tuning for pod-to-pod calls (2s dial timeout); false targets the public internet (5s dial timeout). Both enable aggressive TCP keep-alive probing (15s idle, 5s interval, 3 probes).

func NewInternalHTTPClient added in v0.29.0

func NewInternalHTTPClient(opts ...HTTPClientOption) *http.Client

NewInternalHTTPClient returns a client tuned for pod-to-pod calls through a ClusterIP Service with no mesh or gateway in the path, using NewHTTPTransport with internal set to true and a 10s timeout. Options are applied afterwards, so HTTPClientWithTimeout overrides the timeout.

Create one client per logical upstream at process start and reuse it for the lifetime of the process: the Transport is the connection pool, so a client per request defeats pooling and leaks file descriptors.

func NewServer added in v0.24.0

func NewServer(l *zap.Logger, name, addr string, handler http.Handler, middlewares ...Middleware) *http.Server

NewServer creates and configures an HTTP server for in-cluster traffic listening on addr. handler is wrapped with middlewares using Compose, and net/http errors are logged through l at error level.

The server speaks HTTP/1.1 only and sets conservative timeouts: ReadHeaderTimeout 5s, ReadTimeout 30s, WriteTimeout 60s, IdleTimeout 620s and MaxHeaderBytes 1 MiB. Streaming or large-upload handlers must clear the read or write deadline via http.NewResponseController.

Types

type HTTPClientOption added in v0.6.0

type HTTPClientOption func(*http.Client)

HTTPClientOption configures an http.Client created by NewInternalHTTPClient, NewExternalHTTPClient or NewHTTPClient. Options are applied in order.

Transport options (such as HTTPClientWithMaxConnsPerHost) modify the client's *http.Transport and panic if the transport has already been replaced by a wrapping option such as HTTPClientWithTelemetry or HTTPClientWithRoundTripware, or by a non-*http.Transport set through HTTPClientWithTransport. Apply wrapping options last.

func HTTPClientWithCheckRedirect added in v0.6.0

func HTTPClientWithCheckRedirect(o func(req *http.Request, via []*http.Request) error) HTTPClientOption

HTTPClientWithCheckRedirect sets the client's redirect policy (http.Client.CheckRedirect).

func HTTPClientWithDialContext added in v0.6.0

func HTTPClientWithDialContext(o func(ctx context.Context, network, addr string) (net.Conn, error)) HTTPClientOption

HTTPClientWithDialContext sets the transport's dial function for unencrypted TCP connections.

func HTTPClientWithDialTLSContext added in v0.6.0

func HTTPClientWithDialTLSContext(o func(ctx context.Context, network, addr string) (net.Conn, error)) HTTPClientOption

HTTPClientWithDialTLSContext sets the transport's dial function for TLS connections to non-proxied HTTPS requests.

func HTTPClientWithDisableCompression added in v0.6.0

func HTTPClientWithDisableCompression(o bool) HTTPClientOption

HTTPClientWithDisableCompression sets whether the transport refrains from requesting gzip-compressed responses.

func HTTPClientWithDisableKeepAlives added in v0.6.0

func HTTPClientWithDisableKeepAlives(o bool) HTTPClientOption

HTTPClientWithDisableKeepAlives sets whether the transport disables HTTP keep-alives and uses each connection for a single request only.

func HTTPClientWithExpectContinueTimeout added in v0.6.0

func HTTPClientWithExpectContinueTimeout(o time.Duration) HTTPClientOption

HTTPClientWithExpectContinueTimeout sets how long the transport waits for a server's first response headers after sending "Expect: 100-continue".

func HTTPClientWithForceAttemptHTTP2 deprecated added in v0.6.0

func HTTPClientWithForceAttemptHTTP2(o bool) HTTPClientOption

HTTPClientWithForceAttemptHTTP2 enables HTTP/2 negotiation.

The transport consults Protocols first, so this setting is ignored when Protocols is set, which is the case for NewInternalHTTPClient and NewExternalHTTPClient.

Deprecated: Use HTTPClientWithProtocols instead.

func HTTPClientWithGetProxyConnectHeader added in v0.6.0

func HTTPClientWithGetProxyConnectHeader(o func(ctx context.Context, proxyURL *url.URL, target string) (http.Header, error)) HTTPClientOption

HTTPClientWithGetProxyConnectHeader sets the function returning headers sent to a proxy in CONNECT requests.

func HTTPClientWithIdleConnTimeout added in v0.6.0

func HTTPClientWithIdleConnTimeout(o time.Duration) HTTPClientOption

HTTPClientWithIdleConnTimeout sets how long an idle pooled connection is kept.

Keep it below the peer's idle timeout, otherwise the client races the remote FIN and observes spurious EOF on the next request. Relevant peer values: http.Server.IdleTimeout (unbounded by default, so set it explicitly), AWS ALB 60s, conntrack/NAT 300s.

func HTTPClientWithJar added in v0.6.0

func HTTPClientWithJar(o http.CookieJar) HTTPClientOption

HTTPClientWithJar sets the client's cookie jar.

func HTTPClientWithMaxConnsPerHost added in v0.6.0

func HTTPClientWithMaxConnsPerHost(o int) HTTPClientOption

HTTPClientWithMaxConnsPerHost caps total (idle plus in-use) connections per host, providing backpressure instead of unbounded fan-out during a latency spike. Requests block waiting for a free connection once the cap is reached.

func HTTPClientWithMaxIdleConns added in v0.6.0

func HTTPClientWithMaxIdleConns(o int) HTTPClientOption

HTTPClientWithMaxIdleConns caps pooled idle connections across all hosts. Zero means no limit.

func HTTPClientWithMaxIdleConnsPerHost added in v0.6.0

func HTTPClientWithMaxIdleConnsPerHost(o int) HTTPClientOption

HTTPClientWithMaxIdleConnsPerHost caps pooled idle connections per host.

The net/http default is 2, which serializes concurrent calls and causes constant dial churn. For in-cluster upstreams it also concentrates all load on two pods, because kube-proxy chooses a backend per connection.

func HTTPClientWithMaxResponseHeaderBytes added in v0.6.0

func HTTPClientWithMaxResponseHeaderBytes(o int64) HTTPClientOption

HTTPClientWithMaxResponseHeaderBytes caps response headers from a peer we do not control. The net/http default is a permissive 10 MiB.

func HTTPClientWithProtocols added in v0.29.0

func HTTPClientWithProtocols(o *http.Protocols) HTTPClientOption

HTTPClientWithProtocols pins the wire protocols. Requires Go 1.24 or newer.

func HTTPClientWithProxy added in v0.6.0

func HTTPClientWithProxy(o func(request *http.Request) (*url.URL, error)) HTTPClientOption

HTTPClientWithProxy sets the transport's proxy selection function.

func HTTPClientWithProxyConnectHeader added in v0.6.0

func HTTPClientWithProxyConnectHeader(o http.Header) HTTPClientOption

HTTPClientWithProxyConnectHeader sets the headers sent to proxies in CONNECT requests.

func HTTPClientWithReadBufferSize added in v0.6.0

func HTTPClientWithReadBufferSize(o int) HTTPClientOption

HTTPClientWithReadBufferSize sets the size of the transport's read buffer in bytes.

func HTTPClientWithResponseHeaderTimeout added in v0.6.0

func HTTPClientWithResponseHeaderTimeout(o time.Duration) HTTPClientOption

HTTPClientWithResponseHeaderTimeout bounds the wait between finishing the request and receiving the response status line. It catches upstreams that accept the connection and then go quiet. It does not bound reading the body, so it is safe for streaming responses.

func HTTPClientWithRoundTripware added in v0.6.0

func HTTPClientWithRoundTripware(l *zap.Logger, roundTripware ...roundtripware.RoundTripware) HTTPClientOption

HTTPClientWithRoundTripware wraps the transport with the given roundtripware.RoundTripware, using l for logging. Apply after all transport-tuning options.

func HTTPClientWithTLSClientConfig added in v0.6.0

func HTTPClientWithTLSClientConfig(o *tls.Config) HTTPClientOption

HTTPClientWithTLSClientConfig sets the transport's TLS configuration.

func HTTPClientWithTLSHandshakeTimeout added in v0.6.0

func HTTPClientWithTLSHandshakeTimeout(o time.Duration) HTTPClientOption

HTTPClientWithTLSHandshakeTimeout sets the transport's TLS handshake timeout.

func HTTPClientWithTLSNextProto added in v0.6.0

func HTTPClientWithTLSNextProto(o map[string]func(authority string, c *tls.Conn) http.RoundTripper) HTTPClientOption

HTTPClientWithTLSNextProto sets the transport's TLS ALPN protocol upgrade handlers (http.Transport.TLSNextProto).

func HTTPClientWithTelemetry added in v0.11.4

func HTTPClientWithTelemetry(opts ...otelhttp.Option) HTTPClientOption

HTTPClientWithTelemetry wraps the transport with OTel instrumentation. Apply after all transport-tuning options.

If a retrying round tripper is also in play, put telemetry outermost so it reports one span per logical call rather than one per attempt.

Spans are named "HTTP GET" by default. Pass otelhttp.WithSpanNameFormatter returning "{method} {url.template}" (e.g. "GET /prices/{sku}"); never use the URL path, as it makes span names unbounded.

func HTTPClientWithTimeout added in v0.6.0

func HTTPClientWithTimeout(o time.Duration) HTTPClientOption

HTTPClientWithTimeout sets the client's overall request timeout (http.Client.Timeout).

func HTTPClientWithTransport added in v0.6.0

func HTTPClientWithTransport(o http.RoundTripper) HTTPClientOption

HTTPClientWithTransport replaces the client's transport. Transport options applied afterwards panic unless o is an *http.Transport.

func HTTPClientWithWriteBufferSize added in v0.6.0

func HTTPClientWithWriteBufferSize(o int) HTTPClientOption

HTTPClientWithWriteBufferSize sets the size of the transport's write buffer in bytes.

func HTTPClientWithoutCrossHostRedirects added in v0.29.0

func HTTPClientWithoutCrossHostRedirects(v int) HTTPClientOption

HTTPClientWithoutCrossHostRedirects stops the client following a redirect to a different host, and caps redirect depth at v. When either limit is hit the last response is returned with its body unclosed, as for http.ErrUseLastResponse.

type Middleware added in v0.24.0

type Middleware func(l *zap.Logger, name string, next http.Handler) http.Handler

Middleware wraps next with additional request handling. l is the logger and name the name of the service the handler belongs to.

Directories

Path Synopsis
Package context provides helpers to store and retrieve request-scoped identifiers in a context.Context: the referer, request ID, session ID and tracking ID.
Package context provides helpers to store and retrieve request-scoped identifiers in a context.Context: the referer, request ID, session ID and tracking ID.
Package cookie provides a declarative helper to read, write and delete an HTTP cookie with consistent attributes.
Package cookie provides a declarative helper to read, write and delete an HTTP cookie with consistent attributes.
Package log provides helpers to attach a github.com/foomo/keel/log.Labeler to an HTTP request context, so code handling the request can collect additional log fields for it.
Package log provides helpers to attach a github.com/foomo/keel/log.Labeler to an HTTP request context, so code handling the request can collect additional log fields for it.
Package middleware provides HTTP server middlewares for keel services.
Package middleware provides HTTP server middlewares for keel services.
Package provider provides pluggable value providers for HTTP middleware and round-trippers, such as RequestID generators.
Package provider provides pluggable value providers for HTTP middleware and round-trippers, such as RequestID generators.
Package rbac provides path-based, role-driven access control rules for HTTP requests.
Package rbac provides path-based, role-driven access control rules for HTTP requests.
Package roundtripware provides HTTP client middlewares, called RoundTripwares, that wrap an net/http.RoundTripper.
Package roundtripware provides HTTP client middlewares, called RoundTripwares, that wrap an net/http.RoundTripper.

Jump to

Keyboard shortcuts

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