Go API Documentation

github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy

No package summary is available.

Package

Files: 13. Third party imports: 10. Imports from organisation: 0. Tests: 0. Benchmarks: 0.

Constants

Vars

bufPool is used for buffering requests and responses.

errNoUpstream occurs when there are no upstream available.

Hop-by-hop headers. These are removed when sent to the backend. As of RFC 7230, hop-by-hop headers are required to appear in the Connection header field. These are the headers defined by the obsoleted RFC 2616 (section 13.5.1) and are used for backward compatibility.

hosts is the global repository for hosts that are currently in use by active configuration(s). This allows the state of remote hosts to be preserved through config reloads.

Mapping of the canonical form of the headers, to the RFC 6455 form, i.e. WebSocket with uppercase 'S'.

Types

AUpstreams

AUpstreams provides upstreams from A/AAAA lookups. Results are cached and refreshed at the configured refresh interval.

Field name Field type Comment
Name

string

The domain name to look up.

Port

string

The port to use with the upstreams. Default: 80

Refresh

caddy.Duration

The interval at which to refresh the A lookup. Results are cached between lookups. Default: 1m

Resolver

*UpstreamResolver

Configures the DNS resolver used to resolve the domain name to A records.

DialTimeout

caddy.Duration

If Resolver is configured, how long to wait before timing out trying to connect to the DNS server.

FallbackDelay

caddy.Duration

If Resolver is configured, how long to wait before spawning an RFC 6555 Fast Fallback connection. A negative value disables this.

Versions

*IPVersions

The IP versions to resolve for. By default, both "ipv4" and "ipv6" will be enabled, which correspond to A and AAAA records respectively.

resolver

*net.Resolver

No comment on field.
logger

*zap.Logger

No comment on field.

ActiveHealthChecks

ActiveHealthChecks holds configuration related to active health checks (that is, health checks which occur in a background goroutine independently).

Field name Field type Comment
Path

string

Deprecated: Use 'uri' instead. This field will be removed. TODO: remove this field

URI

string

The URI (path and query) to use for health checks

Upstream

string

The host:port to use (if different from the upstream's dial address) for health checks. This should be used in tandem with health_header and {http.reverse_proxy.active.target_upstream}. This can be helpful when creating an intermediate service to do a more thorough health check. If upstream is set, the active health check port is ignored.

Port

int

The port to use (if different from the upstream's dial address) for health checks. If active upstream is set, this value is ignored.

Headers

http.Header

HTTP headers to set on health check requests.

Method

string

The HTTP method to use for health checks (default "GET").

Body

string

The body to send with the health check request.

FollowRedirects

bool

Whether to follow HTTP redirects in response to active health checks (default off).

Interval

caddy.Duration

How frequently to perform active health checks (default 30s).

Timeout

caddy.Duration

How long to wait for a response from a backend before considering it unhealthy (default 5s).

Passes

int

Number of consecutive health check passes before marking a previously unhealthy backend as healthy again (default 1).

Fails

int

Number of consecutive health check failures before marking a previously healthy backend as unhealthy (default 1).

MaxSize

int64

The maximum response body to download from the backend during a health check.

ExpectStatus

int

The HTTP status code to expect from a healthy backend.

ExpectBody

string

A regular expression against which to match the response body of a healthy backend.

uri

*url.URL

No comment on field.
httpClient

*http.Client

No comment on field.
bodyRegexp

*regexp.Regexp

No comment on field.
logger

*zap.Logger

No comment on field.

CircuitBreaker

CircuitBreaker is a type that can act as an early-warning system for the health checker when backends are getting overloaded. This interface is still experimental and is subject to change.

Field name Field type Comment
type

any

No comment on field.

ClientIPHashSelection

ClientIPHashSelection is a policy that selects a host based on hashing the client IP of the request, as determined by the HTTP app's trusted proxies settings.

CookieHashSelection

CookieHashSelection is a policy that selects a host based on a given cookie name.

Field name Field type Comment
Name

string

The HTTP cookie name whose value is to be hashed and used for upstream selection.

Secret

string

Secret to hash (Hmac256) chosen upstream in cookie

MaxAge

caddy.Duration

The cookie's Max-Age before it expires. Default is no expiry.

FallbackRaw

json.RawMessage

The fallback policy to use if the cookie is not present. Defaults to random.

fallback

Selector

No comment on field.

CopyResponseHandler

CopyResponseHandler is a special HTTP handler which may only be used within reverse_proxy's handle_response routes, to copy the proxy response. EXPERIMENTAL, subject to change.

Field name Field type Comment
StatusCode

caddyhttp.WeakString

To write the upstream response's body but with a different status code, set this field to the desired status code.

ctx

caddy.Context

No comment on field.

CopyResponseHeadersHandler

CopyResponseHeadersHandler is a special HTTP handler which may only be used within reverse_proxy's handle_response routes, to copy headers from the proxy response. EXPERIMENTAL; subject to change.

Field name Field type Comment
Include

[]string

A list of header fields to copy from the response. Cannot be defined at the same time as Exclude.

Exclude

[]string

A list of header fields to skip copying from the response. Cannot be defined at the same time as Include.

includeMap

map[string]struct{}

No comment on field.
excludeMap

map[string]struct{}

No comment on field.
ctx

caddy.Context

No comment on field.

DialError

DialError is an error that specifically occurs in a call to Dial or DialContext.

Field name Field type Comment

error

No comment on field.

DialInfo

DialInfo contains information needed to dial a connection to an upstream host. This information may be different than that which is represented in a URL (for example, unix sockets don't have a host that can be represented in a URL, but they certainly have a network name and address).

Field name Field type Comment
Upstream

*Upstream

Upstream is the Upstream associated with this DialInfo. It may be nil.

Network

string

The network to use. This should be one of the values that is accepted by net.Dial: https://golang.org/pkg/net/#Dial

Address

string

The address to dial. Follows the same semantics and rules as net.Dial.

Host

string

Host and Port are components of Address.

FirstSelection

FirstSelection is a policy that selects the first available host.

HTTPTransport

HTTPTransport is essentially a configuration wrapper for http.Transport. It defines a JSON structure useful when configuring the HTTP transport for Caddy's reverse proxy. It builds its http.Transport at Provision.

Field name Field type Comment
Resolver

*UpstreamResolver

Configures the DNS resolver used to resolve the IP address of upstream hostnames.

TLS

*TLSConfig

Configures TLS to the upstream. Setting this to an empty struct is sufficient to enable TLS with reasonable defaults.

KeepAlive

*KeepAlive

Configures HTTP Keep-Alive (enabled by default). Should only be necessary if rigorous testing has shown that tuning this helps improve performance.

Compression

*bool

Whether to enable compression to upstream. Default: true

MaxConnsPerHost

int

Maximum number of connections per host. Default: 0 (no limit)

ProxyProtocol

string

If non-empty, which PROXY protocol version to send when connecting to an upstream. Default: off.

ForwardProxyURL

string

URL to the server that the HTTP transport will use to proxy requests to the upstream. See http.Transport.Proxy for information regarding supported protocols. This value takes precedence over HTTP_PROXY, etc.

Providing a value to this parameter results in requests flowing through the reverse_proxy in the following way:

User Agent -> reverse_proxy -> forward_proxy_url -> upstream

Default: http.ProxyFromEnvironment DEPRECATED: Use NetworkProxyRaw|network_proxy instead. Subject to removal.

DialTimeout

caddy.Duration

How long to wait before timing out trying to connect to an upstream. Default: 3s.

FallbackDelay

caddy.Duration

How long to wait before spawning an RFC 6555 Fast Fallback connection. A negative value disables this. Default: 300ms.

ResponseHeaderTimeout

caddy.Duration

How long to wait for reading response headers from server. Default: No timeout.

ExpectContinueTimeout

caddy.Duration

The length of time to wait for a server's first response headers after fully writing the request headers if the request has a header "Expect: 100-continue". Default: No timeout.

MaxResponseHeaderSize

int64

The maximum bytes to read from response headers. Default: 10MiB.

WriteBufferSize

int

The size of the write buffer in bytes. Default: 4KiB.

ReadBufferSize

int

The size of the read buffer in bytes. Default: 4KiB.

ReadTimeout

caddy.Duration

The maximum time to wait for next read from backend. Default: no timeout.

WriteTimeout

caddy.Duration

The maximum time to wait for next write to backend. Default: no timeout.

Versions

[]string

The versions of HTTP to support. As a special case, "h2c" can be specified to use H2C (HTTP/2 over Cleartext) to the upstream (this feature is experimental and subject to change or removal). Default: ["1.1", "2"]

EXPERIMENTAL: "3" enables HTTP/3, but it must be the only version specified if enabled. Additionally, HTTPS must be enabled to the upstream as HTTP/3 requires TLS. Subject to change or removal while experimental.

LocalAddress

string

Specify the address to bind to when connecting to an upstream. In other words, it is the address the upstream sees as the remote address.

Transport

*http.Transport

The pre-configured underlying HTTP transport.

NetworkProxyRaw

json.RawMessage

The module that provides the network (forward) proxy URL that the HTTP transport will use to proxy requests to the upstream. See http.Transport.Proxy for information regarding supported protocols.

Providing a value to this parameter results in requests flowing through the reverse_proxy in the following way:

User Agent -> reverse_proxy -> [proxy provided by the module] -> upstream

If nil, defaults to reading the HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables.

h2cTransport

*http2.Transport

No comment on field.
h3Transport

*http3.Transport

No comment on field.

Handler

Handler implements a highly configurable and production-ready reverse proxy.

Upon proxying, this module sets the following placeholders (which can be used both within and after this handler; for example, in response headers):

Placeholder | Description ------------|------------- {http.reverse_proxy.upstream.address} | The full address to the upstream as given in the config {http.reverse_proxy.upstream.hostport} | The host:port of the upstream {http.reverse_proxy.upstream.host} | The host of the upstream {http.reverse_proxy.upstream.port} | The port of the upstream {http.reverse_proxy.upstream.requests} | The approximate current number of requests to the upstream {http.reverse_proxy.upstream.max_requests} | The maximum approximate number of requests allowed to the upstream {http.reverse_proxy.upstream.fails} | The number of recent failed requests to the upstream {http.reverse_proxy.upstream.latency} | How long it took the proxy upstream to write the response header. {http.reverse_proxy.upstream.latency_ms} | Same as 'latency', but in milliseconds. {http.reverse_proxy.upstream.duration} | Time spent proxying to the upstream, including writing response body to client. {http.reverse_proxy.upstream.duration_ms} | Same as 'upstream.duration', but in milliseconds. {http.reverse_proxy.duration} | Total time spent proxying, including selecting an upstream, retries, and writing response. {http.reverse_proxy.duration_ms} | Same as 'duration', but in milliseconds. {http.reverse_proxy.retries} | The number of retries actually performed to communicate with an upstream.

Field name Field type Comment
TransportRaw

json.RawMessage

Configures the method of transport for the proxy. A transport is what performs the actual "round trip" to the backend. The default transport is plaintext HTTP.

CBRaw

json.RawMessage

A circuit breaker may be used to relieve pressure on a backend that is beginning to exhibit symptoms of stress or latency. By default, there is no circuit breaker.

LoadBalancing

*LoadBalancing

Load balancing distributes load/requests between backends.

HealthChecks

*HealthChecks

Health checks update the status of backends, whether they are up or down. Down backends will not be proxied to.

Upstreams

UpstreamPool

Upstreams is the static list of backends to proxy to.

DynamicUpstreamsRaw

json.RawMessage

A module for retrieving the list of upstreams dynamically. Dynamic upstreams are retrieved at every iteration of the proxy loop for each request (i.e. before every proxy attempt within every request). Active health checks do not work on dynamic upstreams, and passive health checks are only effective on dynamic upstreams if the proxy server is busy enough that concurrent requests to the same backends are continuous. Instead of health checks for dynamic upstreams, it is recommended that the dynamic upstream module only return available backends in the first place.

FlushInterval

caddy.Duration

Adjusts how often to flush the response buffer. By default, no periodic flushing is done. A negative value disables response buffering, and flushes immediately after each write to the client. This option is ignored when the upstream's response is recognized as a streaming response, or if its content length is -1; for such responses, writes are flushed to the client immediately.

TrustedProxies

[]string

A list of IP ranges (supports CIDR notation) from which X-Forwarded-* header values should be trusted. By default, no proxies are trusted, so existing values will be ignored when setting these headers. If the proxy is trusted, then existing values will be used when constructing the final header values.

Headers

*headers.Handler

Headers manipulates headers between Caddy and the backend. By default, all headers are passed-thru without changes, with the exceptions of special hop-by-hop headers.

X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host are also set implicitly.

RequestBuffers

int64

If nonzero, the entire request body up to this size will be read and buffered in memory before being proxied to the backend. This should be avoided if at all possible for performance reasons, but could be useful if the backend is intolerant of read latency or chunked encodings.

ResponseBuffers

int64

If nonzero, the entire response body up to this size will be read and buffered in memory before being proxied to the client. This should be avoided if at all possible for performance reasons, but could be useful if the backend has tighter memory constraints.

StreamTimeout

caddy.Duration

If nonzero, streaming requests such as WebSockets will be forcibly closed at the end of the timeout. Default: no timeout.

StreamCloseDelay

caddy.Duration

If nonzero, streaming requests such as WebSockets will not be closed when the proxy config is unloaded, and instead the stream will remain open until the delay is complete. In other words, enabling this prevents streams from closing when Caddy's config is reloaded. Enabling this may be a good idea to avoid a thundering herd of reconnecting clients which had their connections closed by the previous config closing. Default: no delay.

Rewrite

*rewrite.Rewrite

If configured, rewrites the copy of the upstream request. Allows changing the request method and URI (path and query). Since the rewrite is applied to the copy, it does not persist past the reverse proxy handler. If the method is changed to GET or HEAD, the request body will not be copied to the backend. This allows a later request handler -- either in a handle_response route, or after -- to read the body. By default, no rewrite is performed, and the method and URI from the incoming request is used as-is for proxying.

HandleResponse

[]caddyhttp.ResponseHandler

List of handlers and their associated matchers to evaluate after successful roundtrips. The first handler that matches the response from a backend will be invoked. The response body from the backend will not be written to the client; it is up to the handler to finish handling the response. If passive health checks are enabled, any errors from the handler chain will not affect the health status of the backend.

Three new placeholders are available in this handler chain:

  • {http.reverse_proxy.status_code} The status code from the response
  • {http.reverse_proxy.status_text} The status text from the response
  • {http.reverse_proxy.header.*} The headers from the response
VerboseLogs

bool

If set, the proxy will write very detailed logs about its inner workings. Enable this only when debugging, as it will produce a lot of output.

EXPERIMENTAL: This feature is subject to change or removal.

Transport

http.RoundTripper

No comment on field.
CB

CircuitBreaker

No comment on field.
DynamicUpstreams

UpstreamSource

No comment on field.
trustedProxies

[]netip.Prefix

Holds the parsed CIDR ranges from TrustedProxies

responseMatchers

map[string]caddyhttp.ResponseMatcher

Holds the named response matchers from the Caddyfile while adapting

handleResponseSegments

[]*caddyfile.Dispenser

Holds the handle_response Caddyfile tokens while adapting

connections

map[io.ReadWriteCloser]openConnection

Stores upgraded requests (hijacked connections) for proper cleanup

connectionsCloseTimer

*time.Timer

No comment on field.
connectionsMu

*sync.Mutex

No comment on field.
ctx

caddy.Context

No comment on field.
logger

*zap.Logger

No comment on field.
events

*caddyevents.App

No comment on field.

HeaderHashSelection

HeaderHashSelection is a policy that selects a host based on a given request header.

Field name Field type Comment
Field

string

The HTTP header field whose value is to be hashed and used for upstream selection.

FallbackRaw

json.RawMessage

The fallback policy to use if the header is not present. Defaults to random.

fallback

Selector

No comment on field.

HealthChecks

HealthChecks configures active and passive health checks.

Field name Field type Comment
Active

*ActiveHealthChecks

Active health checks run in the background on a timer. To minimally enable active health checks, set either path or port (or both). Note that active health check status (healthy/unhealthy) is stored per-proxy-handler, not globally; this allows different handlers to use different criteria to decide what defines a healthy backend.

Active health checks do not run for dynamic upstreams.

Passive

*PassiveHealthChecks

Passive health checks monitor proxied requests for errors or timeouts. To minimally enable passive health checks, specify at least an empty config object with fail_duration > 0. Passive health check state is shared (stored globally), so a failure from one handler will be counted by all handlers; but the tolerances or standards for what defines healthy/unhealthy backends is configured per-proxy-handler.

Passive health checks technically do operate on dynamic upstreams, but are only effective for very busy proxies where the list of upstreams is mostly stable. This is because the shared/global state of upstreams is cleaned up when the upstreams are no longer used. Since dynamic upstreams are allocated dynamically at each request (specifically, each iteration of the proxy loop per request), they are also cleaned up after every request. Thus, if there is a moment when no requests are actively referring to a particular upstream host, the passive health check state will be reset because it will be garbage-collected. It is usually better for the dynamic upstream module to only return healthy, available backends instead.

Host

Host is the basic, in-memory representation of the state of a remote host. Its fields are accessed atomically and Host values must not be copied.

Field name Field type Comment
numRequests

int64

No comment on field.
fails

int64

No comment on field.
activePasses

int64

No comment on field.
activeFails

int64

No comment on field.

IPHashSelection

IPHashSelection is a policy that selects a host based on hashing the remote IP of the request.

IPVersions

This type doesn't have documentation.

Field name Field type Comment
IPv4

*bool

No comment on field.
IPv6

*bool

No comment on field.

KeepAlive

KeepAlive holds configuration pertaining to HTTP Keep-Alive.

Field name Field type Comment
Enabled

*bool

Whether HTTP Keep-Alive is enabled. Default: true

ProbeInterval

caddy.Duration

How often to probe for liveness. Default: 30s.

MaxIdleConns

int

Maximum number of idle connections. Default: 0, which means no limit.

MaxIdleConnsPerHost

int

Maximum number of idle connections per host. Default: 32.

IdleConnTimeout

caddy.Duration

How long connections should be kept alive when idle. Default: 2m.

LeastConnSelection

LeastConnSelection is a policy that selects the host with the least active requests. If multiple hosts have the same fewest number, one is chosen randomly. The term "conn" or "connection" is used in this policy name due to its similar meaning in other software, but our load balancer actually counts active requests rather than connections, since these days requests are multiplexed onto shared connections.

LoadBalancing

LoadBalancing has parameters related to load balancing.

Field name Field type Comment
SelectionPolicyRaw

json.RawMessage

A selection policy is how to choose an available backend. The default policy is random selection.

Retries

int

How many times to retry selecting available backends for each request if the next available host is down. If try_duration is also configured, then retries may stop early if the duration is reached. By default, retries are disabled (zero).

TryDuration

caddy.Duration

How long to try selecting available backends for each request if the next available host is down. Clients will wait for up to this long while the load balancer tries to find an available upstream host. If retries is also configured, tries may stop early if the maximum retries is reached. By default, retries are disabled (zero duration).

TryInterval

caddy.Duration

How long to wait between selecting the next host from the pool. Default is 250ms if try_duration is enabled, otherwise zero. Only relevant when a request to an upstream host fails. Be aware that setting this to 0 with a non-zero try_duration can cause the CPU to spin if all backends are down and latency is very low.

RetryMatchRaw

caddyhttp.RawMatcherSets

A list of matcher sets that restricts with which requests retries are allowed. A request must match any of the given matcher sets in order to be retried if the connection to the upstream succeeded but the subsequent round-trip failed. If the connection to the upstream failed, a retry is always allowed. If unspecified, only GET requests will be allowed to be retried. Note that a retry is done with the next available host according to the load balancing policy.

SelectionPolicy

Selector

No comment on field.
RetryMatch

caddyhttp.MatcherSets

No comment on field.

MultiUpstreams

MultiUpstreams is a single dynamic upstream source that aggregates the results of multiple dynamic upstream sources. All configured sources will be queried in order, with their results appended to the end of the list. Errors returned from individual sources will be logged and the next source will continue to be invoked.

This module makes it easy to implement redundant cluster failovers, especially in conjunction with the first load balancing policy: if the first source returns an error or no upstreams, the second source's upstreams will be used naturally.

Field name Field type Comment
SourcesRaw

[]json.RawMessage

The list of upstream source modules to get upstreams from. They will be queried in order, with their results appended in the order they are returned.

sources

[]UpstreamSource

No comment on field.
logger

*zap.Logger

No comment on field.

PassiveHealthChecks

PassiveHealthChecks holds configuration related to passive health checks (that is, health checks which occur during the normal flow of request proxying).

Field name Field type Comment
FailDuration

caddy.Duration

How long to remember a failed request to a backend. A duration > 0 enables passive health checking. Default is 0.

MaxFails

int

The number of failed requests within the FailDuration window to consider a backend as "down". Must be >= 1; default is 1. Requires that FailDuration be > 0.

UnhealthyRequestCount

int

Limits the number of simultaneous requests to a backend by marking the backend as "down" if it has this many concurrent requests or more.

UnhealthyStatus

[]int

Count the request as failed if the response comes back with one of these status codes.

UnhealthyLatency

caddy.Duration

Count the request as failed if the response takes at least this long to receive.

logger

*zap.Logger

No comment on field.

ProxyProtocolInfo

ProxyProtocolInfo contains information needed to write proxy protocol to a connection to an upstream host.

Field name Field type Comment
AddrPort

netip.AddrPort

No comment on field.

QueryHashSelection

QueryHashSelection is a policy that selects a host based on a given request query parameter.

Field name Field type Comment
Key

string

The query key whose value is to be hashed and used for upstream selection.

FallbackRaw

json.RawMessage

The fallback policy to use if the query key is not present. Defaults to random.

fallback

Selector

No comment on field.

RandomChoiceSelection

RandomChoiceSelection is a policy that selects two or more available hosts at random, then chooses the one with the least load.

Field name Field type Comment
Choose

int

The size of the sub-pool created from the larger upstream pool. The default value is 2 and the maximum at selection time is the size of the upstream pool.

RandomSelection

RandomSelection is a policy that selects an available host at random.

RoundRobinSelection

RoundRobinSelection is a policy that selects a host based on round-robin ordering.

Field name Field type Comment
robin

uint32

No comment on field.

SRVUpstreams

SRVUpstreams provides upstreams from SRV lookups. The lookup DNS name can be configured either by its individual parts (that is, specifying the service, protocol, and name separately) to form the standard "_service._proto.name" domain, or the domain can be specified directly in name by leaving service and proto empty. See RFC 2782.

Lookups are cached and refreshed at the configured refresh interval.

Returned upstreams are sorted by priority and weight.

Field name Field type Comment
Service

string

The service label.

Proto

string

The protocol label; either tcp or udp.

Name

string

The name label; or, if service and proto are empty, the entire domain name to look up.

Refresh

caddy.Duration

The interval at which to refresh the SRV lookup. Results are cached between lookups. Default: 1m

GracePeriod

caddy.Duration

If > 0 and there is an error with the lookup, continue to use the cached results for up to this long before trying again, (even though they are stale) instead of returning an error to the client. Default: 0s.

Resolver

*UpstreamResolver

Configures the DNS resolver used to resolve the SRV address to SRV records.

DialTimeout

caddy.Duration

If Resolver is configured, how long to wait before timing out trying to connect to the DNS server.

FallbackDelay

caddy.Duration

If Resolver is configured, how long to wait before spawning an RFC 6555 Fast Fallback connection. A negative value disables this.

resolver

*net.Resolver

No comment on field.
logger

*zap.Logger

No comment on field.

Selector

Selector selects an available upstream from the pool.

Field name Field type Comment
type

any

No comment on field.

TLSConfig

TLSConfig holds configuration related to the TLS configuration for the transport/client.

Field name Field type Comment
CARaw

json.RawMessage

Certificate authority module which provides the certificate pool of trusted certificates

RootCAPool

[]string

Deprecated: Use the ca field with the tls.ca_pool.source.inline module instead. Optional list of base64-encoded DER-encoded CA certificates to trust.

RootCAPEMFiles

[]string

Deprecated: Use the ca field with the tls.ca_pool.source.file module instead. List of PEM-encoded CA certificate files to add to the same trust store as RootCAPool (or root_ca_pool in the JSON).

ClientCertificateFile

string

PEM-encoded client certificate filename to present to servers.

ClientCertificateKeyFile

string

PEM-encoded key to use with the client certificate.

ClientCertificateAutomate

string

If specified, Caddy will use and automate a client certificate with this subject name.

InsecureSkipVerify

bool

If true, TLS verification of server certificates will be disabled. This is insecure and may be removed in the future. Do not use this option except in testing or local development environments.

HandshakeTimeout

caddy.Duration

The duration to allow a TLS handshake to a server. Default: No timeout.

ServerName

string

The server name used when verifying the certificate received in the TLS handshake. By default, this will use the upstream address' host part. You only need to override this if your upstream address does not match the certificate the upstream is likely to use. For example if the upstream address is an IP address, then you would need to configure this to the hostname being served by the upstream server. Currently, this does not support placeholders because the TLS config is not provisioned on each connection, so a static value must be used.

Renegotiation

string

TLS renegotiation level. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. The level can be:

  • "never": (the default) disables renegotiation.
  • "once": allows a remote server to request renegotiation once per connection.
  • "freely": allows a remote server to repeatedly request renegotiation.
ExceptPorts

[]string

Skip TLS ports specifies a list of upstream ports on which TLS should not be attempted even if it is configured. Handy when using dynamic upstreams that return HTTP and HTTPS endpoints too. When specified, TLS will automatically be configured on the transport. The value can be a list of any valid tcp port numbers, default empty.

Curves

[]string

The list of elliptic curves to support. Caddy's defaults are modern and secure.

TLSTransport

TLSTransport is implemented by transports that are capable of using TLS.

Field name Field type Comment
type

any

No comment on field.

URIHashSelection

URIHashSelection is a policy that selects a host by hashing the request URI.

Upstream

Upstream bridges this proxy's configuration to the state of the backend host it is correlated with. Upstream values must not be copied.

Field name Field type Comment

*Host

No comment on field.
Dial

string

The network address to dial to connect to the upstream. Must represent precisely one socket (i.e. no port ranges). A valid network address either has a host and port or is a unix socket address.

Placeholders may be used to make the upstream dynamic, but be aware of the health check implications of this: a single upstream that represents numerous (perhaps arbitrary) backends can be considered down if one or enough of the arbitrary backends is down. Also be aware of open proxy vulnerabilities.

MaxRequests

int

The maximum number of simultaneous requests to allow to this upstream. If set, overrides the global passive health check UnhealthyRequestCount value.

activeHealthCheckPort

int

No comment on field.
activeHealthCheckUpstream

string

No comment on field.
healthCheckPolicy

*PassiveHealthChecks

No comment on field.
cb

CircuitBreaker

No comment on field.
unhealthy

int32

No comment on field.

UpstreamPool

UpstreamPool is a collection of upstreams.

Field name Field type Comment
type

[]*Upstream

No comment on field.

UpstreamResolver

UpstreamResolver holds the set of addresses of DNS resolvers of upstream addresses

Field name Field type Comment
Addresses

[]string

The addresses of DNS resolvers to use when looking up the addresses of proxy upstreams. It accepts network addresses with port range of only 1. If the host is an IP address, it will be dialed directly to resolve the upstream server. If the host is not an IP address, the addresses are resolved using the name resolution convention of the Go standard library. If the array contains more than 1 resolver address, one is chosen at random.

netAddrs

[]caddy.NetworkAddress

No comment on field.

UpstreamSource

UpstreamSource gets the list of upstreams that can be used when proxying a request. Returned upstreams will be load balanced and health-checked. This should be a very fast function -- instant if possible -- and the return value must be as stable as possible. In other words, the list of upstreams should ideally not change much across successive calls. If the list of upstreams changes or the ordering is not stable, load balancing will suffer. This function may be called during each retry, multiple times per request, and as such, needs to be instantaneous. The returned slice will not be modified.

Field name Field type Comment
type

any

No comment on field.

WeightedRoundRobinSelection

WeightedRoundRobinSelection is a policy that selects a host based on weighted round-robin ordering.

Field name Field type Comment
Weights

[]int

The weight of each upstream in order, corresponding with the list of upstreams configured.

index

uint32

No comment on field.
totalWeight

int

No comment on field.

aLookup

This type doesn't have documentation.

Field name Field type Comment
aUpstreams

AUpstreams

No comment on field.
freshness

time.Time

No comment on field.
upstreams

[]Upstream

No comment on field.

adminUpstreams

adminUpstreams is a module that provides the /reverse_proxy/upstreams endpoint for the Caddy admin API. This allows for checking the health of configured reverse proxy upstreams in the pool.

bodyReadCloser

bodyReadCloser is a reader that, upon closing, will return its buffer to the pool and close the underlying body reader.

Field name Field type Comment

io.Reader

No comment on field.
buf

*bytes.Buffer

No comment on field.
body

io.ReadCloser

No comment on field.

h2ReadWriteCloser

This type doesn't have documentation.

Field name Field type Comment

io.ReadCloser

No comment on field.

http.ResponseWriter

No comment on field.

handleResponseContext

handleResponseContext carries some contextual information about the current proxy handling.

Field name Field type Comment
handler

*Handler

handler is the active proxy handler instance, so that routes like copy_response may inherit some config options and have access to handler methods.

response

*http.Response

response is the actual response received from the proxy roundtrip, to potentially be copied if a copy_response handler is in the handle_response routes.

start

time.Time

start is the time just before the proxy roundtrip was performed, used for logging.

logger

*zap.Logger

logger is the prepared logger which is used to write logs with the request, duration, and selected upstream attached.

isFinalized

bool

isFinalized is whether the response has been finalized, i.e. copied and closed, to make sure that it doesn't happen twice.

maxLatencyWriter

This type doesn't have documentation.

Field name Field type Comment
dst

io.Writer

No comment on field.
flush

func() error

No comment on field.
latency

time.Duration

No comment on field.
mu

sync.Mutex

No comment on field.
t

*time.Timer

No comment on field.
flushPending

bool

No comment on field.
logger

*zap.Logger

No comment on field.

metricsUpstreamsHealthyUpdater

This type doesn't have documentation.

Field name Field type Comment
handler

*Handler

No comment on field.

openConnection

openConnection maps an open connection to an optional function for graceful close.

Field name Field type Comment
conn

io.ReadWriteCloser

No comment on field.
gracefulClose

func() error

No comment on field.

parsedAddr

This type doesn't have documentation.

Field name Field type Comment
network

string

No comment on field.
valid

bool

No comment on field.

roundtripSucceededError

roundtripSucceededError is an error type that is returned if the roundtrip succeeded, but an error occurred after-the-fact.

Field name Field type Comment

error

No comment on field.

srvLookup

This type doesn't have documentation.

Field name Field type Comment
srvUpstreams

SRVUpstreams

No comment on field.
freshness

time.Time

No comment on field.
upstreams

[]Upstream

No comment on field.

switchProtocolCopier

switchProtocolCopier exists so goroutines proxying data back and forth have nice names in stacks.

Field name Field type Comment
user

io.ReadWriteCloser

No comment on field.
wg

*sync.WaitGroup

No comment on field.

tcpRWTimeoutConn

tcpRWTimeoutConn enforces read/write timeouts for a TCP connection. If it fails to set deadlines, the error is logged but does not abort the read/write attempt (ignoring the error is consistent with what the standard library does: https://github.com/golang/go/blob/c5da4fb7ac5cb7434b41fc9a1df3bee66c7f1a4d/src/net/http/server.go#L981-L986)

Field name Field type Comment

*net.TCPConn

No comment on field.
readTimeout

time.Duration

No comment on field.
logger

*zap.Logger

No comment on field.

upstreamStatus

upstreamStatus holds the status of a particular upstream

Field name Field type Comment
Address

string

No comment on field.
NumRequests

int

No comment on field.
Fails

int

No comment on field.

Functions

func GetDialInfo

GetDialInfo gets the upstream dialing info out of the context, and returns true if there was a valid value; false otherwise.

Uses: caddyhttp.GetVar.

func (*AUpstreams) Provision

Uses: context.Context, net.Conn, net.DefaultResolver, net.Dialer, net.Resolver, time.Duration, time.Minute, weakrand.Intn.

func (*AUpstreams) UnmarshalCaddyfile

UnmarshalCaddyfile deserializes Caddyfile tokens into h.

dynamic a [<name> <port] {
    name                <name>
    port                <port>
    refresh             <interval>
    resolvers           <resolvers...>
    dial_timeout        <timeout>
    dial_fallback_delay <timeout>
    versions            ipv4|ipv6
}

func (*ActiveHealthChecks) IsEnabled

IsEnabled checks if the active health checks have the minimum config necessary to be enabled.

func (*ActiveHealthChecks) Provision

Provision ensures that a is set up properly before use.

Uses: fmt.Errorf, http.Client, http.ErrUseLastResponse, http.Header, http.MethodGet, http.Request, regexp.Compile, time.Duration, time.Second, url.Parse.

func (*ClientIPHashSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*CookieHashSelection) Provision

Provision sets up the module.

Uses: caddyconfig.JSONModuleObject, fmt.Errorf.

func (*CookieHashSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax:

lb_policy cookie [<name> [<secret>]] {
	fallback <policy>
	max_age <duration>
}

By default name is lb

func (*CopyResponseHandler) Provision

Provision ensures that h is set up properly before use.

func (*CopyResponseHandler) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:

copy_response [<matcher>] [<status>] {
    status <status>
}

Uses: caddyhttp.WeakString, strconv.Atoi.

func (*CopyResponseHeadersHandler) Provision

Provision ensures that h is set up properly before use.

Uses: http.CanonicalHeaderKey.

func (*CopyResponseHeadersHandler) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:

copy_response_headers [<matcher>] {
    include <fields...>
    exclude <fields...>
}

func (*CopyResponseHeadersHandler) Validate

Validate ensures the h's configuration is valid.

Uses: fmt.Errorf.

func (*FirstSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*HTTPTransport) EnableTLS

EnableTLS enables TLS on the transport.

func (*HTTPTransport) NewTransport

NewTransport builds a standard-lib-compatible http.Transport value from h.

Uses: caddyconfig.JSONModuleObject, caddyhttp.GetVar, context.CancelFunc, context.Context, context.WithTimeout, fmt.Errorf, http.ProxyFromEnvironment, http.Transport, http2.ConfigureTransport, http2.Transport, http3.Transport, net.Addr, net.Conn, net.Dialer, net.IPv4zero, net.IPv6zero, net.ResolveTCPAddr, net.ResolveUnixAddr, net.Resolver, net.TCPAddr, net.TCPConn, network.ProxyFromURL, proxyproto.HeaderProxyFromAddrs, slices.Contains, strings.Contains, strings.HasPrefix, time.Duration, time.Minute, time.Second, tls.Client, tls.Config, weakrand.Intn, zap.Any.

func (*HTTPTransport) Provision

Provision sets up h.Transport with a *http.Transport that is ready to use.

func (*HTTPTransport) RoundTrip

RoundTrip implements http.RoundTripper.

func (*HTTPTransport) SetScheme

SetScheme ensures that the outbound request req has the scheme set in its URL; the underlying http.Transport requires a scheme to be set.

This method may be used by other transport modules that wrap/use this one.

func (*HTTPTransport) UnmarshalCaddyfile

UnmarshalCaddyfile deserializes Caddyfile tokens into h.

transport http {
    read_buffer             <size>
    write_buffer            <size>
    max_response_header     <size>
    network_proxy           <module> {
        ...
    }
    dial_timeout            <duration>
    dial_fallback_delay     <duration>
    response_header_timeout <duration>
    expect_continue_timeout <duration>
    resolvers               <resolvers...>
    tls
    tls_client_auth <automate_name> | <cert_file> <key_file>
    tls_insecure_skip_verify
    tls_timeout <duration>
    tls_trusted_ca_certs <cert_files...>
    tls_trust_pool <module> {
        ...
    }
    tls_server_name <sni>
    tls_renegotiation <level>
    tls_except_ports <ports...>
    keepalive [off|<duration>]
    keepalive_interval <interval>
    keepalive_idle_conns <max_count>
    keepalive_idle_conns_per_host <count>
    versions <versions...>
    compression off
    max_conns_per_host <count>
    max_idle_conns_per_host <count>
}

Uses: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, caddytls.CA, humanize.ParseBytes, network.ProxyFromURL, strconv.Atoi.

func (*Handler) Cleanup

Cleanup cleans up the resources made by h.

func (*Handler) FinalizeUnmarshalCaddyfile

FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which requires having an httpcaddyfile.Helper to function, to parse subroutes.

Uses: caddyhttp.ResponseHandler, caddyhttp.ResponseMatcher, caddyhttp.Subroute, httpcaddyfile.ParseSegmentAsSubroute, strings.HasPrefix.

func (*Handler) Provision

Provision ensures that h is set up properly before use.

Uses: caddyevents.App, fmt.Errorf, http.RoundTripper, io.ReadWriteCloser, netip.ParseAddr, netip.ParsePrefix, netip.PrefixFrom, strings.Contains, sync.Mutex, time.Millisecond.

func (*Handler) ServeHTTP

Uses: base64.StdEncoding, bytes.NewReader, caddyhttp.Error, caddyhttp.SetVar, fmt.Errorf, http.MethodConnect, http.MethodGet, http.NoBody, http.StatusInternalServerError, io.NopCloser, rand.Read, time.Duration, time.Now, time.Since, zap.Duration, zap.Error, zapcore.DebugLevel.

func (*Handler) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:

reverse_proxy [<matcher>] [<upstreams...>] {
    # backends
    to      <upstreams...>
    dynamic <name> [...]

    # load balancing
    lb_policy <name> [<options...>]
    lb_retries <retries>
    lb_try_duration <duration>
    lb_try_interval <interval>
    lb_retry_match <request-matcher>

    # active health checking
    health_uri          <uri>
    health_port         <port>
    health_interval     <interval>
    health_passes       <num>
    health_fails        <num>
    health_timeout      <duration>
    health_status       <status>
    health_body         <regexp>
    health_method       <value>
    health_request_body <value>
    health_follow_redirects
    health_headers {
        <field> [<values...>]
    }

    # passive health checking
    fail_duration     <duration>
    max_fails         <num>
    unhealthy_status  <status>
    unhealthy_latency <duration>
    unhealthy_request_count <num>

    # streaming
    flush_interval     <duration>
    request_buffers    <size>
    response_buffers   <size>
    stream_timeout     <duration>
    stream_close_delay <duration>
    verbose_logs

    # request manipulation
    trusted_proxies [private_ranges] <ranges...>
    header_up   [+|-]<field> [<value|regexp> [<replacement>]]
    header_down [+|-]<field> [<value|regexp> [<replacement>]]
    method <method>
    rewrite <to>

    # round trip
    transport <name> {
        ...
    }

    # optionally intercept responses from upstream
    @name {
        status <code...>
        header <field> [<value>]
    }
    replace_status [<matcher>] <status_code>
    handle_response [<matcher>] {
        <directives...>

        # special directives only available in handle_response
        copy_response [<matcher>] [<status>] {
            status <status>
        }
        copy_response_headers [<matcher>] {
            include <fields...>
            exclude <fields...>
        }
    }
}

Proxy upstream addresses should be network dial addresses such as host:port, or a URL such as scheme://host:port. Scheme and port may be inferred from other parts of the address/URL; if either are missing, defaults to HTTP.

The FinalizeUnmarshalCaddyfile method should be called after this to finalize parsing of "handle_response" blocks, if possible.

Uses: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, caddyhttp.ParseCaddyfileNestedMatcherSet, caddyhttp.ParseNamedResponseMatcher, caddyhttp.ResponseHandler, caddyhttp.ResponseMatcher, caddyhttp.WeakString, fmt.Errorf, fmt.Sprint, headers.CaddyfileHeaderOp, headers.Handler, headers.HeaderOps, headers.RespHeaderOps, http.Header, http.RoundTripper, humanize.ParseBytes, net.SplitHostPort, reflect.DeepEqual, rewrite.Rewrite, strconv.Atoi, strings.EqualFold, strings.HasPrefix, strings.HasSuffix.

func (*HeaderHashSelection) Provision

Provision sets up the module.

Uses: caddyconfig.JSONModuleObject, fmt.Errorf.

func (*HeaderHashSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*Host) Fails

Fails returns the number of recent failures with the upstream.

Uses: atomic.LoadInt64.

func (*Host) NumRequests

NumRequests returns the number of active requests to the upstream.

Uses: atomic.LoadInt64.

func (*IPHashSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*LeastConnSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*MultiUpstreams) Provision

Uses: fmt.Errorf.

func (*MultiUpstreams) UnmarshalCaddyfile

UnmarshalCaddyfile deserializes Caddyfile tokens into h.

dynamic multi {
    <source> [...]
}

Uses: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule.

func (*QueryHashSelection) Provision

Provision sets up the module.

Uses: caddyconfig.JSONModuleObject, fmt.Errorf.

func (*QueryHashSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*RandomChoiceSelection) Provision

Provision sets up r.

func (*RandomChoiceSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

Uses: strconv.Atoi.

func (*RandomSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*RoundRobinSelection) Select

Select returns an available host, if any.

Uses: atomic.AddUint32.

func (*RoundRobinSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*SRVUpstreams) Provision

Uses: context.Context, net.Conn, net.DefaultResolver, net.Dialer, net.Resolver, time.Duration, time.Minute, weakrand.Intn.

func (*SRVUpstreams) UnmarshalCaddyfile

UnmarshalCaddyfile deserializes Caddyfile tokens into h.

dynamic srv [<name>] {
    service             <service>
    proto               <proto>
    name                <name>
    refresh             <interval>
    resolvers           <resolvers...>
    dial_timeout        <timeout>
    dial_fallback_delay <timeout>
    grace_period        <duration>
}

func (*TLSConfig) MakeTLSClientConfig

MakeTLSClientConfig returns a tls.Config usable by a client to a backend. If there is no custom TLS configuration, a nil config may be returned.

Uses: caddytls.AllMatchingCertificates, caddytls.CA, caddytls.SupportedCurves, caddytls.TLS, fmt.Errorf, os.ReadFile, reflect.DeepEqual, tls.Certificate, tls.CertificateRequestInfo, tls.Config, tls.CurveID, tls.LoadX509KeyPair, tls.RenegotiateFreelyAsClient, tls.RenegotiateNever, tls.RenegotiateOnceAsClient, x509.NewCertPool.

func (*URIHashSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

func (*Upstream) Available

Available returns true if the remote host is available to receive requests. This is the method that should be used by selection policies, etc. to determine if a backend should be able to be sent a request.

func (*Upstream) Full

Full returns true if the remote host cannot receive more requests at this time.

func (*Upstream) Healthy

Healthy returns true if the remote host is currently known to be healthy or "up". It consults the circuit breaker, if any.

func (*Upstream) String

(pointer receiver necessary to avoid a race condition, since copying the Upstream reads the 'unhealthy' field which is accessed atomically)

func (*UpstreamResolver) ParseAddresses

ParseAddresses parses all the configured network addresses and ensures they're ready to be used.

Uses: fmt.Errorf.

func (*WeightedRoundRobinSelection) Provision

Provision sets up r.

func (*WeightedRoundRobinSelection) Select

Select returns an available host, if any.

Uses: atomic.AddUint32.

func (*WeightedRoundRobinSelection) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the module from Caddyfile tokens.

Uses: strconv.Atoi.

func (*maxLatencyWriter) Write

Uses: time.AfterFunc, zap.Duration, zap.Error, zap.Int, zapcore.DebugLevel.

func (*tcpRWTimeoutConn) Read

Uses: time.Now, zap.Error, zapcore.ErrorLevel.

func (*tcpRWTimeoutConn) Write

Uses: time.Now, zap.Error, zapcore.ErrorLevel.

func (AUpstreams) CaddyModule

CaddyModule returns the Caddy module information.

func (AUpstreams) GetUpstreams

Uses: net.JoinHostPort, time.Now, zap.String, zapcore.DebugLevel.

func (AUpstreams) String

Uses: net.JoinHostPort.

func (ClientIPHashSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (ClientIPHashSelection) Select

Select returns an available host, if any.

Uses: caddyhttp.ClientIPVarKey, caddyhttp.GetVar, net.SplitHostPort.

func (CookieHashSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (CookieHashSelection) Select

Select returns an available host, if any.

Uses: caddyhttp.GetVar, caddyhttp.TrustedProxyVarKey, http.Cookie, http.SameSiteNoneMode, http.SetCookie, time.Duration.

func (CopyResponseHandler) CaddyModule

CaddyModule returns the Caddy module information.

func (CopyResponseHandler) ServeHTTP

ServeHTTP implements the Handler interface.

Uses: caddyhttp.Error, fmt.Errorf, http.StatusInternalServerError, strconv.Atoi.

func (CopyResponseHeadersHandler) CaddyModule

CaddyModule returns the Caddy module information.

func (CopyResponseHeadersHandler) ServeHTTP

ServeHTTP implements the Handler interface.

Uses: caddyhttp.Error, fmt.Errorf, http.StatusInternalServerError.

func (DialInfo) String

String returns the Caddy network address form by joining the network and address with a forward slash.

func (FirstSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (FirstSelection) Select

Select returns an available host, if any.

func (HTTPTransport) CaddyModule

CaddyModule returns the Caddy module information.

func (HTTPTransport) Cleanup

Cleanup implements caddy.CleanerUpper and closes any idle connections.

func (HTTPTransport) TLSEnabled

TLSEnabled returns true if TLS is enabled.

func (Handler) CaddyModule

CaddyModule returns the Caddy module information.

func (HeaderHashSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (HeaderHashSelection) Select

Select returns an available host, if any.

func (IPHashSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (IPHashSelection) Select

Select returns an available host, if any.

Uses: net.SplitHostPort.

func (LeastConnSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (LeastConnSelection) Select

Select selects the up host with the least number of connections in the pool. If more than one host has the same least number of connections, one of the hosts is chosen at random.

Uses: weakrand.Int.

func (MultiUpstreams) CaddyModule

CaddyModule returns the Caddy module information.

func (MultiUpstreams) GetUpstreams

Uses: context.Canceled, zap.Error, zap.Int, zapcore.ErrorLevel, zapcore.WarnLevel.

func (QueryHashSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (QueryHashSelection) Select

Select returns an available host, if any.

Uses: strings.Join.

func (RandomChoiceSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (RandomChoiceSelection) Select

Select returns an available host, if any.

Uses: weakrand.Intn.

func (RandomChoiceSelection) Validate

Validate ensures that r's configuration is valid.

Uses: fmt.Errorf.

func (RandomSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (RandomSelection) Select

Select returns an available host, if any.

func (RoundRobinSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (SRVUpstreams) CaddyModule

CaddyModule returns the Caddy module information.

func (SRVUpstreams) GetUpstreams

Uses: net.JoinHostPort, strconv.Itoa, time.Duration, time.Now, zap.Error, zap.String, zap.Uint16, zapcore.DebugLevel, zapcore.ErrorLevel, zapcore.WarnLevel.

func (SRVUpstreams) String

func (URIHashSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (URIHashSelection) Select

Select returns an available host, if any.

func (WeightedRoundRobinSelection) CaddyModule

CaddyModule returns the Caddy module information.

func (adminUpstreams) CaddyModule

CaddyModule returns the Caddy module information.

func (adminUpstreams) Routes

Routes returns a route for the /reverse_proxy/upstreams endpoint.

func (bodyReadCloser) Close

func (h2ReadWriteCloser) Write

Uses: http.NewResponseController.

Private functions

func allHeaderValues

allHeaderValues gets all values for a given header field, joined by a comma and space if more than one is set. If the header field is nil, then the omit is true, meaning some earlier logic in the server wanted to prevent this header from getting written at all. If the header is empty, then ok is false. Callers should still check that the value is not empty (the header field may be set but have an empty value).

References: http.CanonicalHeaderKey, strings.Join.

func allNew

func asciiEqualFold

asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t are equal, ASCII-case-insensitively.

func asciiIsPrint

asciiIsPrint returns whether s is ASCII and printable according to https://tools.ietf.org/html/rfc20#section-4.2.

func asciiLower

asciiLower returns the ASCII lowercase version of b.

func cloneRequest

cloneRequest makes a semi-deep clone of origReq.

Most of this code is borrowed from the Go stdlib reverse proxy, but we make a shallow-ish clone the request (deep clone only the headers and URL) so we can avoid manipulating the original request when using it to proxy upstream. This prevents request corruption and data races.

References: http.Request, url.URL, url.Userinfo.

func cmdReverseProxy

References: caddyconfig.JSON, caddyconfig.JSONModuleObject, caddyhttp.App, caddyhttp.AutoHTTPSConfig, caddyhttp.DefaultHTTPPort, caddyhttp.DefaultHTTPSPort, caddyhttp.MatchHost, caddyhttp.Route, caddyhttp.RouteList, caddyhttp.Server, caddyhttp.ServerLogConfig, caddytls.AutomationConfig, caddytls.AutomationPolicy, caddytls.TLS, fmt.Errorf, fmt.Sprint, headers.Handler, headers.HeaderOps, headers.RespHeaderOps, http.Header, httpcaddyfile.ParseAddress, json.RawMessage, strconv.Itoa, strings.Cut, strings.TrimSpace, zap.DebugLevel, zap.String, zap.Strings.

func copyHeader

func decodeBase64DERCert

decodeBase64DERCert base64-decodes, then DER-decodes, certStr.

References: base64.StdEncoding, x509.ParseCertificate.

func hash

hash calculates a fast hash based on s.

func hashCookie

hashCookie hashes (HMAC 256) some data with the secret

References: hex.EncodeToString, hmac.New, sha256.New.

func hostByHashing

hostByHashing returns an available host from pool based on a hashable string s.

func init

func initReverseProxyMetrics

References: errors.Is, prometheus.AlreadyRegisteredError, prometheus.GaugeOpts, prometheus.NewGaugeVec.

func isWebsocket

isWebsocket returns true if r looks to be an upgrade request for WebSockets. It is a fairly naive check.

References: httpguts.HeaderValuesContainsToken.

func lastHeaderValue

lastHeaderValue gets the last value for a given header field if more than one is set. If the header field is nil, then the omit is true, meaning some earlier logic in the server wanted to prevent this header from getting written at all. If the header is empty, then ok is false. Callers should still check that the value is not empty (the header field may be set but have an empty value).

References: http.CanonicalHeaderKey.

func leastRequests

leastRequests returns the host with the least number of active requests to it. If more than one host has the same least number of active requests, then one of those is chosen at random.

References: weakrand.Intn.

func loadFallbackPolicy

References: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule.

func maskBytes

Copied from https://github.com/gorilla/websocket/blob/v1.5.0/mask.go

References: unsafe.Pointer.

func newMaskKey

Copied from https://github.com/gorilla/websocket/blob/v1.5.0/conn.go#L184

References: weakrand.Uint32.

func newMetricsUpstreamsHealthyUpdater

func normalizeWebsocketHeaders

normalizeWebsocketHeaders ensures we use the standard casing as per RFC 6455, i.e. WebSocket with uppercase 'S'. Most servers don't care about this difference (read headers case insensitively), but some do, so this maximizes compatibility with upstreams. See https://github.com/caddyserver/caddy/pull/6621

func parseCaddyfile

func parseCopyResponseCaddyfile

func parseCopyResponseHeadersCaddyfile

func parseUpstreamDialAddress

parseUpstreamDialAddress parses configuration inputs for the dial address, including support for a scheme in front as a shortcut for the port number, and a network type, for example 'unix' to dial a unix socket.

References: fmt.Errorf, strings.Contains, strings.Count, strings.LastIndex, strings.ReplaceAll, url.Parse.

func removeConnectionHeaders

removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h. See RFC 7230, section 6.1

References: strings.Split, textproto.TrimString.

func resolveIpVersion

func selectRandomHost

selectRandomHost returns a random available host

References: weakrand.Int.

func statusError

statusError returns an error value that has a status code.

References: caddyhttp.Error, context.Canceled, errors.Is, http.StatusBadGateway, http.StatusGatewayTimeout, net.Error, strings.Contains.

func upgradeType

References: httpguts.HeaderValuesContainsToken, strings.ToLower.

func writeCloseControl

writeCloseControl sends a best-effort Close control message to the given WebSocket connection. Thanks to @pascaldekloe who provided inspiration from his simple implementation of this I was able to learn from at: github.com/pascaldekloe/websocket. Further work for handling masking taken from github.com/gorilla/websocket.

func shouldUseTLS

shouldUseTLS returns true if TLS should be used for req.

References: slices.Contains.

func activeHealthChecker

activeHealthChecker runs active health checks on a regular basis and blocks until h.HealthChecks.Active.stopChan is closed.

References: debug.Stack, time.Duration, time.NewTicker, zap.Any, zap.ByteString, zapcore.ErrorLevel.

func cleanupConnections

cleanupConnections closes hijacked connections. Depending on the value of StreamCloseDelay it does that either immediately or sets up a timer that will do that later.

References: time.AfterFunc, time.Duration, zap.Duration, zap.Error, zapcore.DebugLevel, zapcore.ErrorLevel.

func closeConnections

closeConnections immediately closes all hijacked connections (both to client and backend).

func countFailure

countFailure is used with passive health checks. It remembers 1 failure for upstream for the configured duration. If passive health checks are disabled or failure expiry is 0, this is a no-op.

References: debug.Stack, time.Duration, time.NewTimer, zap.Any, zap.ByteString, zap.Error, zap.String, zapcore.ErrorLevel.

func doActiveHealthCheck

doActiveHealthCheck performs a health check to upstream which can be reached at address hostAddr. The actual address for the request will be built according to active health checker config. The health status of the host will be updated according to whether it passes the health check. An error is returned only if the health check fails to occur or if marking the host's health status fails.

References: caddyhttp.OriginalRequestCtxKey, caddyhttp.StatusCodeMatches, caddyhttp.VarsCtxKey, context.WithValue, fmt.Errorf, http.NewRequestWithContext, io.Copy, io.Discard, io.LimitReader, io.ReadAll, io.Reader, net.JoinHostPort, net.SplitHostPort, slices.Contains, strconv.Itoa, strings.NewReader, url.URL, zap.Error, zap.Int, zap.String, zapcore.ErrorLevel, zapcore.InfoLevel.

func doActiveHealthCheckForAllHosts

doActiveHealthCheckForAllHosts immediately performs a health checks for all upstream hosts configured by h.

References: debug.Stack, zap.Any, zap.ByteString, zap.Error, zap.String, zapcore.ErrorLevel.

func finalizeResponse

finalizeResponse prepares and copies the response.

References: fmt.Sprintf, http.ErrAbortHandler, http.NewResponseController, http.StatusSwitchingProtocols, http.TrailerPrefix, strings.HasPrefix, strings.Index, strings.Join, strings.ToUpper, sync.WaitGroup, time.Since, zap.Error, zapcore.DebugLevel, zapcore.WarnLevel.

func handleUpgradeResponse

References: bufio.NewReadWriter, bufio.NewReaderSize, bufio.NewWriterSize, bufio.ReadWriter, caddyhttp.GetVar, errors.Is, fmt.Sprintf, http.ErrNotSupported, http.NewResponseController, http.StatusOK, io.ReadCloser, io.ReadWriteCloser, time.Duration, time.NewTimer, time.Now, time.Since, time.Time, zap.DebugLevel, zap.Duration, zap.Error, zap.ErrorLevel, zap.Int, zap.String, zap.Time, zapcore.DebugLevel.

func proxyLoopIteration

proxyLoopIteration implements an iteration of the proxy loop. Despite the enormous amount of local state that has to be passed in, we brought this into its own method so that we could run defer more easily. It returns true when the loop is done and should break; false otherwise. The error value returned should be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break).

References: caddyhttp.Error, caddyhttp.SetVar, context.Canceled, errors.Is, fmt.Errorf, http.Header, http.StatusServiceUnavailable, zap.Error, zap.Int, zap.String, zapcore.DebugLevel, zapcore.ErrorLevel.

func registerConnection

registerConnection holds onto conn so it can be closed in the event of a server shutdown. This is useful because hijacked connections or connections dialed to backends don't close when server is shut down. The caller should call the returned delete() function when the connection is done to remove it from memory.

func reverseProxy

reverseProxy performs a round-trip to the given backend and processes the response with the client. (This method is mostly the beginning of what was borrowed from the net/http/httputil package in the Go standard library which was used as the foundation.)

References: caddyhttp.Error, caddyhttp.LoggableHTTPHeader, caddyhttp.LoggableHTTPRequest, caddyhttp.Server, caddyhttp.ServerCtxKey, caddyhttp.StatusCodeMatches, context.WithValue, http.Header, http.StatusInternalServerError, httptrace.ClientTrace, httptrace.WithClientTrace, strconv.Atoi, strings.Join, sync.Mutex, textproto.MIMEHeader, time.Duration, time.Now, time.Since, zap.Duration, zap.Error, zap.Int, zap.Object, zap.String, zapcore.DebugLevel.

func activeHealthFails

activeHealthFails returns the number of consecutive active health check failures with the upstream.

References: atomic.LoadInt64.

func activeHealthPasses

activeHealthPasses returns the number of consecutive active health check passes with the upstream.

References: atomic.LoadInt64.

func countFail

countFail mutates the recent failures count by delta. It returns an error if the adjustment fails.

References: atomic.AddInt64, fmt.Errorf.

func countHealthFail

countHealthFail mutates the recent failures count by delta. It returns an error if the adjustment fails.

References: atomic.AddInt64, fmt.Errorf.

func countHealthPass

countHealthPass mutates the recent passes count by delta. It returns an error if the adjustment fails.

References: atomic.AddInt64, fmt.Errorf.

func countRequest

countRequest mutates the active request count by delta. It returns an error if the adjustment fails.

References: atomic.AddInt64, fmt.Errorf.

func resetHealth

resetHealth resets the health check counters.

References: atomic.StoreInt64.

func fillDialInfo

fillDialInfo returns a filled DialInfo for upstream u, using the request context. Note that the returned value is not a pointer.

References: fmt.Errorf, strconv.Itoa.

func fillHost

func healthy

healthy returns true if the upstream is not actively marked as unhealthy. (This returns the status only from the "active" health checks.)

References: atomic.LoadInt32.

func setHealthy

SetHealthy sets the upstream has healthy or unhealthy and returns true if the new value is different. This sets the status only for the "active" health checks.

References: atomic.CompareAndSwapInt32.

func delayedFlush

func stop

func init

References: debug.Stack, time.NewTicker, time.Second, zap.Any, zap.ByteString, zapcore.ErrorLevel.

func update

References: prometheus.Labels.

func addForwardedHeaders

addForwardedHeaders adds the de-facto standard X-Forwarded-* headers to the request before it is sent upstream.

These headers are security sensitive, so care is taken to only use existing values for these headers from the incoming request if the client IP is trusted (i.e. coming from a trusted proxy sitting in front of this server). If the request didn't have the headers at all, then they will be added with the values that we can glean from the request.

References: caddyhttp.GetVar, caddyhttp.TrustedProxyVarKey, fmt.Errorf, net.SplitHostPort, netip.ParseAddr, strings.Cut.

func bufferedBody

bufferedBody reads originalBody into a buffer with maximum size of limit (-1 for unlimited), then returns a reader for the buffer along with how many bytes were buffered. Always close the return value when done with it, just like if it was the original body! If limit is 0 (which it shouldn't be), this function returns its input; i.e. is a no-op, for safety. Otherwise, it returns bodyReadCloser, the original body will be closed and body will be nil if it's explicitly configured to buffer all or EOF is reached when reading. TODO: the error during reading is discarded if the limit is negative, should the error be propagated to upstream/downstream?

References: bytes.Buffer, io.Copy, io.CopyN, io.EOF, io.MultiReader.

func copyBuffer

copyBuffer returns any write errors or non-EOF read errors, and the amount of bytes written.

References: context.Canceled, fmt.Errorf, io.EOF, io.ErrShortWrite, zap.Error, zap.Int, zap.Int64, zapcore.DebugLevel, zapcore.ErrorLevel.

func copyResponse

References: http.NewResponseController, io.Writer, time.AfterFunc, zap.Logger, zap.NewNop.

func directRequest

directRequest modifies only req.URL so that it points to the upstream in the given DialInfo. It must modify ONLY the request URL.

func flushInterval

flushInterval returns the p.FlushInterval value, conditionally overriding its value for a specific request/response.

References: mime.ParseMediaType, time.Duration.

func isBidirectionalStream

isBidirectionalStream returns whether we should work in bi-directional stream mode.

See https://github.com/caddyserver/caddy/pull/3620 for discussion of nuances.

func prepareRequest

prepareRequest clones req so that it can be safely modified without changing the original request or introducing data races. It then modifies it so that it is ready to be proxied, except for directing to a specific upstream. This method adjusts headers and other relevant properties of the cloned request and should be done just once (before proxying) regardless of proxy retries. This assumes that no mutations of the cloned request are performed by h during or after proxying.

References: caddyhttp.ClientIPVarKey, caddyhttp.GetVar, caddyhttp.SetVar, fmt.Sprintf, httpguts.HeaderValuesContainsToken, netip.AddrPortFrom, netip.ParseAddr, netip.ParseAddrPort, strconv.FormatInt.

func provisionUpstream

func tryAgain

tryAgain takes the time that the handler was initially invoked, the amount of retries already performed, as well as any error currently obtained, and the request being tried, and returns true if another attempt should be made at proxying the request. If true is returned, it has already blocked long enough before the next retry (i.e. no more sleeping is needed). If false is returned, the handler should stop trying to proxy the request.

References: caddyhttp.HandlerError, errors.Is, time.Duration, time.NewTimer, time.Since, zap.Error.

func expandedAddr

expandedAddr expands placeholders in the configured SRV domain labels. The return values are: addr, the RFC 2782 representation of the SRV domain; service, the service; proto, the protocol; and name, the name. If su.Service and su.Proto are empty, name will be returned as addr instead.

func formattedAddr

formattedAddr the RFC 2782 representation of the SRV domain, in the form "_service._proto.name".

References: fmt.Sprintf.

func isFresh

References: time.Duration, time.Since.

func handleUpstreams

handleUpstreams reports the status of the reverse proxy upstream pool.

References: fmt.Errorf, http.MethodGet, http.StatusInternalServerError, http.StatusMethodNotAllowed, json.NewEncoder.

func dialAddr

References: net.JoinHostPort, strings.Contains.

func isUnix

func rangedPort

References: strings.Contains.

func replaceablePort

References: strings.Contains.

func isFresh

References: time.Duration, time.Since.

func copyFromBackend

References: io.Copy.

func copyToBackend

References: io.Copy.


Tests

Files: 7. Third party imports: 0. Imports from organisation: 0. Tests: 21. Benchmarks: 0.

Types

zeroReader

This type doesn't have documentation.

Test functions

TestBuffering

References: io.LimitReader, io.NopCloser, io.ReadCloser, testing.T.

TestClientIPHashPolicy

References: caddyhttp.ClientIPVarKey, caddyhttp.SetVar, caddyhttp.VarsCtxKey, context.WithValue, http.NewRequest.

TestCookieHashPolicy

References: context.Background, http.MethodGet, httptest.NewRecorder, httptest.NewRequest.

TestCookieHashPolicyWithFirstFallback

References: caddyconfig.JSONModuleObject, context.Background, http.MethodGet, httptest.NewRecorder, httptest.NewRequest.

TestCookieHashPolicyWithSecureRequest

References: context.Background, http.HandlerFunc, http.MethodGet, http.NewRequest, http.Request, http.ResponseWriter, http.SameSiteNoneMode, httptest.NewTLSServer.

TestEqualFold

References: testing.T.

TestFirstPolicy

References: http.MethodGet, httptest.NewRequest.

TestHTTPTransportUnmarshalCaddyFileWithCaPools

References: caddyfile.Dispenser, caddyfile.NewTestDispenser, fmt.Sprintf, json.RawMessage, reflect.DeepEqual, testing.T.

TestHandlerCopyResponse

References: bytes.NewBuffer, httptest.NewRecorder, strings.Repeat.

TestIPHashPolicy

References: http.NewRequest.

TestIsPrint

References: testing.T.

TestLeastConnPolicy

References: http.NewRequest.

TestLeastRequests

TestParseUpstreamDialAddress

TestQueryHashPolicy

References: context.Background, http.MethodGet, httptest.NewRequest.

TestRandomChoicePolicy

References: http.MethodGet, httptest.NewRequest.

TestResolveIpVersion

TestRoundRobinPolicy

References: http.NewRequest.

TestURIHashPolicy

References: http.MethodGet, httptest.NewRequest.

TestWeightedRoundRobinPolicy

References: http.NewRequest.

TestWeightedRoundRobinPolicyWithZeroWeight

References: http.NewRequest.