Help us shape the future of Go! Take the 2026 Go Developer Survey

httpclient

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package httpclient provides a named HTTP client registry and factory.

Clients are configured once (via ClientSpec) and built by the Registry, which applies global concerns (fixture transports, shared default transport) consistently to every client it produces — whether named or inline.

The package does not define a new interface for consuming HTTP; it produces standard *http.Client instances.

Index

Constants

View Source
const DefaultMaxIdleConnsPerHost = 10

DefaultMaxIdleConnsPerHost is the project-wide default for net/http.Transport.MaxIdleConnsPerHost. Go's stdlib default is 2; parsec raises it to 10 so bursty concurrent callers reuse connections instead of re-establishing TCP+TLS on every request.

Variables

This section is empty.

Functions

func ParseBaseURL added in v0.10.0

func ParseBaseURL(raw string, requireHTTPS bool) (*url.URL, error)

ParseBaseURL validates and parses an origin-form base URL for Lua HTTP resolution. Empty input returns (nil, nil). Allowed forms are scheme + host with no path, or scheme + host + "/" only. Any other path, query, or fragment is rejected so relative Lua URLs join predictably as {base}/path. Scheme must be http or https; user info (user:password@) is not allowed. When requireHTTPS is true, http:// origins are rejected so credential-bearing transports (BearerTransport, HeadersTransport) never resolve relative URLs to plaintext HTTP.

func UsesCredentialTransport added in v0.10.0

func UsesCredentialTransport(client *http.Client) bool

UsesCredentialTransport reports whether the client's transport chain injects HTTP-layer credentials (bearer token or fixed headers). If a new credential-injecting transport type is added (e.g., OAuth2Transport), it would bypass the HTTPS requirement unless the switch is updated.

Types

type BearerTransport

type BearerTransport struct {
	Token string
	Base  http.RoundTripper
}

BearerTransport injects a static Authorization: Bearer header into every request.

func (*BearerTransport) RoundTrip

func (t *BearerTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type CertSource

type CertSource interface {
	// Certificate returns the current client cert+key for TLS handshake.
	Certificate() (tls.Certificate, error)
}

CertSource provides client certificates for mTLS. Implementations may read from files, Vault, K8s secrets, etc.

type ClientName

type ClientName string

ClientName identifies a named HTTP client in configuration.

type ClientSpec

type ClientSpec struct {
	Timeout             time.Duration
	CertSource          CertSource          // nil = no client certificate
	TransportMiddleware TransportMiddleware // nil = no wrapping
	RootCAPath          string              // PEM-encoded CA cert file to trust; empty = system roots
	BaseURL             string              // optional origin for relative Lua URLs; empty = none
	MaxIdleConnsPerHost int                 // 0 = DefaultMaxIdleConnsPerHost
}

ClientSpec holds resolved parameters for building an *http.Client. It is the runtime equivalent of the configuration-level HTTPClientSpec, with durations parsed and abstractions instantiated.

type FileCertSource

type FileCertSource struct {
	CertPath string
	KeyPath  string
}

FileCertSource loads a client certificate and key from disk paths.

func NewFileCertSource

func NewFileCertSource(certPath, keyPath string) *FileCertSource

NewFileCertSource creates a FileCertSource that reads from the given paths.

func (*FileCertSource) Certificate

func (s *FileCertSource) Certificate() (tls.Certificate, error)

Certificate implements CertSource.

type HTTPClientObserver added in v0.6.0

type HTTPClientObserver interface {
	// RequestStarted is called when an outbound HTTP request begins.
	// clientName is the [ClientName] from the registry (empty for inline clients).
	// Returns a potentially modified context and a probe to track the request.
	RequestStarted(ctx context.Context, clientName string, method string, host string) (context.Context, RequestProbe)
}

HTTPClientObserver observes outbound HTTP client requests made via the Registry. Implementations should embed NoOpHTTPClientObserver for forward compatibility with new methods added to this interface.

type HeadersTransport added in v0.7.0

type HeadersTransport struct {
	Headers map[string]string
	Base    http.RoundTripper
}

HeadersTransport injects a fixed set of headers into every request.

func (*HeadersTransport) RoundTrip added in v0.7.0

func (t *HeadersTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type LuaClient added in v0.10.0

type LuaClient struct {
	Client  *http.Client
	BaseURL string
}

LuaClient bundles an *http.Client with an optional base URL for Lua scripts. Relative paths in http.get/post/request resolve against BaseURL; absolute URLs are unchanged. JWT validators and other non-Lua callers use Registry.Get only.

func (LuaClient) HTTPClient added in v0.10.0

func (c LuaClient) HTTPClient() *http.Client

HTTPClient returns the underlying client, or http.DefaultClient when Client is nil.

type NoOpHTTPClientObserver added in v0.6.0

type NoOpHTTPClientObserver struct{}

NoOpHTTPClientObserver is a no-op implementation for forward compatibility and testing.

func (NoOpHTTPClientObserver) RequestStarted added in v0.6.0

RequestStarted returns the context unchanged and a no-op probe.

type NoOpRequestProbe added in v0.6.0

type NoOpRequestProbe struct{}

NoOpRequestProbe is a no-op implementation for forward compatibility.

func (NoOpRequestProbe) ConnectionReused added in v0.6.0

func (NoOpRequestProbe) ConnectionReused(bool)

func (NoOpRequestProbe) End added in v0.6.0

func (NoOpRequestProbe) End()

func (NoOpRequestProbe) Error added in v0.6.0

func (NoOpRequestProbe) Error(error)

func (NoOpRequestProbe) ProtocolVersion added in v0.6.0

func (NoOpRequestProbe) ProtocolVersion(string)

func (NoOpRequestProbe) StatusCode added in v0.6.0

func (NoOpRequestProbe) StatusCode(int)

type Registry

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

Registry builds, stores, and provides named HTTP clients. It is also the factory for inline (anonymous) clients, ensuring global concerns like fixture transports are applied uniformly.

func NewRegistry

func NewRegistry(fixtureTransport http.RoundTripper, opts ...RegistryOption) *Registry

NewRegistry creates a Registry. If fixtureTransport is non-nil, it overrides the base transport for every client built by this registry (hermetic mode).

func (*Registry) BaseURL added in v0.10.0

func (r *Registry) BaseURL(name ClientName) (string, error)

BaseURL returns the configured base URL for a named client. An empty string means no base was set. Returns an error if the name is unknown.

func (*Registry) Build

func (r *Registry) Build(spec ClientSpec) (*http.Client, error)

Build creates an anonymous *http.Client from the given spec, applying all global concerns (fixture transport, etc.). The client is NOT stored in the registry. Use this for inline-defined clients.

func (*Registry) BuildLua added in v0.10.0

func (r *Registry) BuildLua(spec ClientSpec) (LuaClient, error)

BuildLua creates an anonymous client from spec and returns it with its base URL.

func (*Registry) Get

func (r *Registry) Get(name ClientName) (*http.Client, error)

Get retrieves a named client. Returns an error if not found.

func (*Registry) GetLua added in v0.10.0

func (r *Registry) GetLua(name ClientName) (LuaClient, error)

GetLua returns a named client and its optional Lua base URL.

func (*Registry) Register

func (r *Registry) Register(name ClientName, spec ClientSpec) (*http.Client, error)

Register builds a client from spec, stores it by name, and returns it. Returns an error if the name is already registered or the spec is invalid.

type RegistryOption added in v0.6.0

type RegistryOption func(*registryConfig)

RegistryOption configures optional parameters for NewRegistry.

func WithObserver added in v0.6.0

func WithObserver(obs HTTPClientObserver) RegistryOption

WithObserver sets the observer used to instrument outbound HTTP requests. If not provided, no instrumentation is applied.

type RequestProbe added in v0.6.0

type RequestProbe interface {
	// StatusCode records the HTTP response status code.
	StatusCode(code int)

	// Error records a transport-level error (timeout, connection refused, etc.).
	Error(err error)

	// ConnectionReused records whether the underlying TCP connection was
	// reused (true) or newly established (false). Called from an
	// httptrace.ClientTrace.GotConn callback during the round-trip.
	ConnectionReused(reused bool)

	// ProtocolVersion records the negotiated HTTP protocol version
	// (e.g. "HTTP/1.1", "HTTP/2.0") from the response. Only called on
	// successful round-trips; omitted on transport-level errors.
	ProtocolVersion(proto string)

	// End signals the request is complete (for timing). Called via defer.
	End()
}

RequestProbe tracks a single outbound HTTP request. Implementations should embed NoOpRequestProbe for forward compatibility.

type TransportMiddleware

type TransportMiddleware func(base http.RoundTripper) http.RoundTripper

TransportMiddleware wraps a base RoundTripper, returning a decorated one. Used to compose concerns like authentication atop a resolved base transport.

Jump to

Keyboard shortcuts

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