Go API Documentation

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

No package summary is available.

Package

Files: 23. Third party imports: 23. Imports from organisation: 1. Tests: 0. Benchmarks: 0.

Constants

Vars

ErrNotImplemented is returned when an underlying ResponseWriter does not implement the required method.

emptyHandler is used as a no-op handler.

An implicit suffix middleware that, if reached, sets the StatusCode to the error stored in the ErrorCtxKey. This is to prevent situations where the Error chain does not actually handle the error (for instance, it matches only on some errors). See #3053

httpRequestCELType is the type representation of a native HTTP request.

Types

App

App is a robust, production-ready HTTP server.

HTTPS is enabled by default if host matchers with qualifying names are used in any of routes; certificates are automatically provisioned and renewed. Additionally, automatic HTTPS will also enable HTTPS for servers that listen only on the HTTPS port but which do not have any TLS connection policies defined by adding a good, default TLS connection policy.

In HTTP routes, additional placeholders are available (replace any *):

Placeholder | Description ------------|--------------- {http.request.body} | The request body (⚠️ inefficient; use only for debugging) {http.request.cookie.*} | HTTP request cookie {http.request.duration} | Time up to now spent handling the request (after decoding headers from client) {http.request.duration_ms} | Same as 'duration', but in milliseconds. {http.request.uuid} | The request unique identifier {http.request.header.*} | Specific request header field {http.request.host} | The host part of the request's Host header {http.request.host.labels.*} | Request host labels (0-based from right); e.g. for foo.example.com: 0=com, 1=example, 2=foo {http.request.hostport} | The host and port from the request's Host header {http.request.method} | The request method {http.request.orig_method} | The request's original method {http.request.orig_uri} | The request's original URI {http.request.orig_uri.path} | The request's original path {http.request.orig_uri.path.*} | Parts of the original path, split by / (0-based from left) {http.request.orig_uri.path.dir} | The request's original directory {http.request.orig_uri.path.file} | The request's original filename {http.request.orig_uri.query} | The request's original query string (without ?) {http.request.port} | The port part of the request's Host header {http.request.proto} | The protocol of the request {http.request.local.host} | The host (IP) part of the local address the connection arrived on {http.request.local.port} | The port part of the local address the connection arrived on {http.request.local} | The local address the connection arrived on {http.request.remote.host} | The host (IP) part of the remote client's address, if available (not known with HTTP/3 early data) {http.request.remote.port} | The port part of the remote client's address {http.request.remote} | The address of the remote client {http.request.scheme} | The request scheme, typically http or https {http.request.tls.version} | The TLS version name {http.request.tls.cipher_suite} | The TLS cipher suite {http.request.tls.resumed} | The TLS connection resumed a previous connection {http.request.tls.proto} | The negotiated next protocol {http.request.tls.proto_mutual} | The negotiated next protocol was advertised by the server {http.request.tls.server_name} | The server name requested by the client, if any {http.request.tls.client.fingerprint} | The SHA256 checksum of the client certificate {http.request.tls.client.public_key} | The public key of the client certificate. {http.request.tls.client.public_key_sha256} | The SHA256 checksum of the client's public key. {http.request.tls.client.certificate_pem} | The PEM-encoded value of the certificate. {http.request.tls.client.certificate_der_base64} | The base64-encoded value of the certificate. {http.request.tls.client.issuer} | The issuer DN of the client certificate {http.request.tls.client.serial} | The serial number of the client certificate {http.request.tls.client.subject} | The subject DN of the client certificate {http.request.tls.client.san.dns_names.*} | SAN DNS names(index optional) {http.request.tls.client.san.emails.*} | SAN email addresses (index optional) {http.request.tls.client.san.ips.*} | SAN IP addresses (index optional) {http.request.tls.client.san.uris.*} | SAN URIs (index optional) {http.request.uri} | The full request URI {http.request.uri.path} | The path component of the request URI {http.request.uri.path.*} | Parts of the path, split by / (0-based from left) {http.request.uri.path.dir} | The directory, excluding leaf filename {http.request.uri.path.file} | The filename of the path, excluding directory {http.request.uri.query} | The query string (without ?) {http.request.uri.query.*} | Individual query string value {http.response.header.*} | Specific response header field {http.vars.*} | Custom variables in the HTTP handler chain {http.shutting_down} | True if the HTTP app is shutting down {http.time_until_shutdown} | Time until HTTP server shutdown, if scheduled

Field name Field type Comment
HTTPPort

int

HTTPPort specifies the port to use for HTTP (as opposed to HTTPS), which is used when setting up HTTP->HTTPS redirects or ACME HTTP challenge solvers. Default: 80.

HTTPSPort

int

HTTPSPort specifies the port to use for HTTPS, which is used when solving the ACME TLS-ALPN challenges, or whenever HTTPS is needed but no specific port number is given. Default: 443.

GracePeriod

caddy.Duration

GracePeriod is how long to wait for active connections when shutting down the servers. During the grace period, no new connections are accepted, idle connections are closed, and active connections will be given the full length of time to become idle and close. Once the grace period is over, connections will be forcefully closed. If zero, the grace period is eternal. Default: 0.

ShutdownDelay

caddy.Duration

ShutdownDelay is how long to wait before initiating the grace period. When this app is stopping (e.g. during a config reload or process exit), all servers will be shut down. Normally this immediately initiates the grace period. However, if this delay is configured, servers will not be shut down until the delay is over. During this time, servers continue to function normally and allow new connections. At the end, the grace period will begin. This can be useful to allow downstream load balancers time to move this instance out of the rotation without hiccups.

When shutdown has been scheduled, placeholders {http.shutting_down} (bool) and {http.time_until_shutdown} (duration) may be useful for health checks.

Servers

map[string]*Server

Servers is the list of servers, keyed by arbitrary names chosen at your discretion for your own convenience; the keys do not affect functionality.

Metrics

*Metrics

If set, metrics observations will be enabled. This setting is EXPERIMENTAL and subject to change.

ctx

caddy.Context

No comment on field.
logger

*zap.Logger

No comment on field.
tlsApp

*caddytls.TLS

No comment on field.
allCertDomains

map[string]struct{}

used temporarily between phases 1 and 2 of auto HTTPS

AutoHTTPSConfig

AutoHTTPSConfig is used to disable automatic HTTPS or certain aspects of it for a specific server. HTTPS is enabled automatically and by default when qualifying hostnames are available from the config.

Field name Field type Comment
Disabled

bool

If true, automatic HTTPS will be entirely disabled, including certificate management and redirects.

DisableRedir

bool

If true, only automatic HTTP->HTTPS redirects will be disabled, but other auto-HTTPS features will remain enabled.

DisableCerts

bool

If true, automatic certificate management will be disabled, but other auto-HTTPS features will remain enabled.

Skip

[]string

Hosts/domain names listed here will not be included in automatic HTTPS (they will not have certificates loaded nor redirects applied).

SkipCerts

[]string

Hosts/domain names listed here will still be enabled for automatic HTTPS (unless in the Skip list), except that certificates will not be provisioned and managed for these names.

IgnoreLoadedCerts

bool

By default, automatic HTTPS will obtain and renew certificates for qualifying hostnames. However, if a certificate with a matching SAN is already loaded into the cache, certificate management will not be enabled. To force automated certificate management regardless of loaded certificates, set this to true.

CELLibraryProducer

CELLibraryProducer provide CEL libraries that expose a Matcher implementation as a first class function within the CEL expression matcher.

Field name Field type Comment
type

any

No comment on field.

CELMatcherFactory

CELMatcherFactory converts a constant CEL value into a RequestMatcher. Deprecated: Use CELMatcherWithErrorFactory instead.

Field name Field type Comment
type

func(data ref.Val) (RequestMatcher, error)

No comment on field.

CELMatcherWithErrorFactory

CELMatcherWithErrorFactory converts a constant CEL value into a RequestMatcherWithError.

Field name Field type Comment
type

func(data ref.Val) (RequestMatcherWithError, error)

No comment on field.

ExtraLogFields

ExtraLogFields is a list of extra fields to log with every request.

Field name Field type Comment
fields

[]zapcore.Field

No comment on field.

HTTPErrorConfig

HTTPErrorConfig determines how to handle errors from the HTTP handlers.

Field name Field type Comment
Routes

RouteList

The routes to evaluate after the primary handler chain returns an error. In an error route, extra placeholders are available:

Placeholder | Description ------------|--------------- {http.error.status_code} | The recommended HTTP status code {http.error.status_text} | The status text associated with the recommended status code {http.error.message} | The error message {http.error.trace} | The origin of the error {http.error.id} | An identifier for this occurrence of the error

HTTPRedirectListenerWrapper

HTTPRedirectListenerWrapper provides HTTP->HTTPS redirects for connections that come on the TLS port as an HTTP request, by detecting using the first few bytes that it's not a TLS handshake, but instead an HTTP request.

This is especially useful when using a non-standard HTTPS port. A user may simply type the address in their browser without the https:// scheme, which would cause the browser to attempt the connection over HTTP, but this would cause a "Client sent an HTTP request to an HTTPS server" error response.

This listener wrapper must be placed BEFORE the "tls" listener wrapper, for it to work properly.

Field name Field type Comment
MaxHeaderBytes

int64

MaxHeaderBytes is the maximum size to parse from a client's HTTP request headers. Default: 1 MB

Handler

Handler is like http.Handler except ServeHTTP may return an error.

If any handler encounters an error, it should be returned for proper handling. Return values should be propagated down the middleware chain by returning it unchanged. Returned errors should not be re-wrapped if they are already HandlerError values.

Field name Field type Comment
type

any

No comment on field.

HandlerError

HandlerError is a serializable representation of an error from within an HTTP handler.

Field name Field type Comment
Err

error

No comment on field.
StatusCode

int

No comment on field.
ID

string

No comment on field.
Trace

string

No comment on field.

HandlerFunc

HandlerFunc is a convenience type like http.HandlerFunc.

Field name Field type Comment
type

func(http.ResponseWriter, *http.Request) error

No comment on field.

IPRangeSource

IPRangeSource gets a list of IP ranges.

The request is passed as an argument to allow plugin implementations to have more flexibility. But, a plugin MUST NOT modify the request. The caller will have read the r.RemoteAddr before getting IP ranges.

This should be a very fast function -- instant if possible. The list of IP ranges should be sourced as soon as possible if loaded from an external source (i.e. initially loaded during Provisioning), so that it's ready to be used when requests start getting handled. A read lock should probably be used to get the cached value if the ranges can change at runtime (e.g. periodically refreshed). Using a caddy.UsagePool may be a good idea to avoid having refetch the values when a config reload occurs, which would waste time.

If the list of IP ranges cannot be sourced, then provisioning SHOULD fail. Getting the IP ranges at runtime MUST NOT fail, because it would cancel incoming requests. If refreshing the list fails, then the previous list of IP ranges should continue to be returned so that the server can continue to operate normally.

Field name Field type Comment
type

any

No comment on field.

Invoke

Invoke implements a handler that compiles and executes a named route that was defined on the server.

EXPERIMENTAL: Subject to change or removal.

Field name Field type Comment
Name

string

Name is the key of the named route to execute

LoggableHTTPHeader

LoggableHTTPHeader makes an HTTP header loggable with zap.Object(). Headers with potentially sensitive information (Cookie, Set-Cookie, Authorization, and Proxy-Authorization) are logged with empty values.

Field name Field type Comment

http.Header

No comment on field.
ShouldLogCredentials

bool

No comment on field.

LoggableHTTPRequest

LoggableHTTPRequest makes an HTTP request loggable with zap.Object().

Field name Field type Comment

*http.Request

No comment on field.
ShouldLogCredentials

bool

No comment on field.

LoggableStringArray

LoggableStringArray makes a slice of strings marshalable for logging.

Field name Field type Comment
type

[]string

No comment on field.

LoggableTLSConnState

LoggableTLSConnState makes a TLS connection state loggable with zap.Object().

Field name Field type Comment
type

tls.ConnectionState

No comment on field.

MatchClientIP

MatchClientIP matches requests by the client IP address, i.e. the resolved address, considering trusted proxies.

Field name Field type Comment
Ranges

[]string

The IPs or CIDR ranges to match.

cidrs

[]*netip.Prefix

cidrs and zones vars should aligned always in the same length and indexes for matching later

zones

[]string

No comment on field.
logger

*zap.Logger

No comment on field.

MatchExpression

MatchExpression matches requests by evaluating a CEL expression. This enables complex logic to be expressed using a comfortable, familiar syntax. Please refer to the standard definitions of CEL functions and operators.

This matcher's JSON interface is actually a string, not a struct. The generated docs are not correct because this type has custom marshaling logic.

COMPATIBILITY NOTE: This module is still experimental and is not subject to Caddy's compatibility guarantee.

Field name Field type Comment
Expr

string

The CEL expression to evaluate. Any Caddy placeholders will be expanded and situated into proper CEL function calls before evaluating.

Name

string

Name is an optional name for this matcher. This is used to populate the name for regexp matchers that appear in the expression.

expandedExpr

string

No comment on field.
prg

cel.Program

No comment on field.
ta

types.Adapter

No comment on field.
log

*zap.Logger

No comment on field.

MatchRegexp

MatchRegexp is an embedable type for matching using regular expressions. It adds placeholders to the request's replacer.

Field name Field type Comment
Name

string

A unique name for this regular expression. Optional, but useful to prevent overwriting captures from other regexp matchers.

Pattern

string

The regular expression to evaluate, in RE2 syntax, which is the same general syntax used by Go, Perl, and Python. For details, see Go's regexp package. Captures are accessible via placeholders. Unnamed capture groups are exposed as their numeric, 1-based index, while named capture groups are available by the capture group name.

compiled

*regexp.Regexp

No comment on field.

MatchRemoteIP

MatchRemoteIP matches requests by the remote IP address, i.e. the IP address of the direct connection to Caddy.

Field name Field type Comment
Ranges

[]string

The IPs or CIDR ranges to match.

cidrs

[]*netip.Prefix

cidrs and zones vars should aligned always in the same length and indexes for matching later

zones

[]string

No comment on field.
logger

*zap.Logger

No comment on field.

MatchVarsRE

MatchVarsRE matches the value of the context variables by a given regular expression.

Upon a match, it adds placeholders to the request: {http.regexp.name.capture_group} where name is the regular expression's name, and capture_group is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: {http.regexp.capture_group} (potentially leading to collisions).

Field name Field type Comment
type

map[string]*MatchRegexp

No comment on field.

MatcherSet

MatcherSet is a set of matchers which must all match in order for the request to be matched successfully.

Field name Field type Comment
type

[]any

No comment on field.

MatcherSets

MatcherSets is a group of matcher sets capable of checking whether a request matches any of the sets.

Field name Field type Comment
type

[]MatcherSet

No comment on field.

Metrics

Metrics configures metrics observations. EXPERIMENTAL and subject to change or removal.

Field name Field type Comment
PerHost

bool

Enable per-host metrics. Enabling this option may incur high-memory consumption, depending on the number of hosts managed by Caddy.

init

sync.Once

No comment on field.
httpMetrics

*httpMetrics

No comment on field.

Middleware

Middleware chains one Handler to the next by being passed the next Handler in the chain.

Field name Field type Comment
type

func(Handler) Handler

No comment on field.

MiddlewareHandler

MiddlewareHandler is like Handler except it takes as a third argument the next handler in the chain. The next handler will never be nil, but may be a no-op handler if this is the last handler in the chain. Handlers which act as middleware should call the next handler's ServeHTTP method so as to propagate the request down the chain properly. Handlers which act as responders (content origins) need not invoke the next handler, since the last handler in the chain should be the first to write the response.

Field name Field type Comment
type

any

No comment on field.

RawMatcherSets

RawMatcherSets is a group of matcher sets in their raw, JSON form.

Field name Field type Comment
type

[]caddy.ModuleMap

No comment on field.

RequestMatcher

RequestMatcher is a type that can match to a request. A route matcher MUST NOT modify the request, with the only exception being its context.

Deprecated: Matchers should now implement RequestMatcherWithError. You may remove any interface guards for RequestMatcher but keep your Match() methods for backwards compatibility.

Field name Field type Comment
type

any

No comment on field.

RequestMatcherWithError

RequestMatcherWithError is like RequestMatcher but can return an error. An error during matching will abort the request middleware chain and invoke the error middleware chain.

This will eventually replace RequestMatcher. Matcher modules should implement both interfaces, and once all modules have been updated to use RequestMatcherWithError, the RequestMatcher interface may eventually be dropped.

Field name Field type Comment
type

any

No comment on field.

ResponseHandler

ResponseHandler pairs a response matcher with custom handling logic. Either the status code can be changed to something else while using the original response body, or, if a status code is not set, it can execute a custom route list; this is useful for executing handler routes based on the properties of an HTTP response that has not been written out to the client yet.

To use this type, provision it at module load time, then when ready to use, match the response against its matcher; if it matches (or doesn't have a matcher), change the status code on the response if configured; otherwise invoke the routes by calling rh.Routes.Compile(next).ServeHTTP(rw, req) (or similar).

Field name Field type Comment
Match

*ResponseMatcher

The response matcher for this handler. If empty/nil, it always matches.

StatusCode

WeakString

To write the original response body but with a different status code, set this field to the desired status code. If set, this takes priority over routes.

Routes

RouteList

The list of HTTP routes to execute if no status code is specified. If evaluated, the original response body will not be written.

ResponseMatcher

ResponseMatcher is a type which can determine if an HTTP response matches some criteria.

Field name Field type Comment
StatusCode

[]int

If set, one of these status codes would be required. A one-digit status can be used to represent all codes in that class (e.g. 3 for all 3xx codes).

Headers

http.Header

If set, each header specified must be one of the specified values, with the same logic used by the request header matcher.

ResponseRecorder

ResponseRecorder is a http.ResponseWriter that records responses instead of writing them to the client. See docs for NewResponseRecorder for proper usage.

Field name Field type Comment
type

any

No comment on field.

ResponseWriterWrapper

ResponseWriterWrapper wraps an underlying ResponseWriter and promotes its Pusher method as well. To use this type, embed a pointer to it within your own struct type that implements the http.ResponseWriter interface, then call methods on the embedded value.

Field name Field type Comment

http.ResponseWriter

No comment on field.

Route

Route consists of a set of rules for matching HTTP requests, a list of handlers to execute, and optional flow control parameters which customize the handling of HTTP requests in a highly flexible and performant manner.

Field name Field type Comment
Group

string

Group is an optional name for a group to which this route belongs. Grouping a route makes it mutually exclusive with others in its group; if a route belongs to a group, only the first matching route in that group will be executed.

MatcherSetsRaw

RawMatcherSets

The matcher sets which will be used to qualify this route for a request (essentially the "if" statement of this route). Each matcher set is OR'ed, but matchers within a set are AND'ed together.

HandlersRaw

[]json.RawMessage

The list of handlers for this route. Upon matching a request, they are chained together in a middleware fashion: requests flow from the first handler to the last (top of the list to the bottom), with the possibility that any handler could stop the chain and/or return an error. Responses flow back through the chain (bottom of the list to the top) as they are written out to the client.

Not all handlers call the next handler in the chain. For example, the reverse_proxy handler always sends a request upstream or returns an error. Thus, configuring handlers after reverse_proxy in the same route is illogical, since they would never be executed. You will want to put handlers which originate the response at the very end of your route(s). The documentation for a module should state whether it invokes the next handler, but sometimes it is common sense.

Some handlers manipulate the response. Remember that requests flow down the list, and responses flow up the list.

For example, if you wanted to use both templates and encode handlers, you would need to put templates after encode in your route, because responses flow up. Thus, templates will be able to parse and execute the plain-text response as a template, and then return it up to the encode handler which will then compress it into a binary format.

If templates came before encode, then encode would write a compressed, binary-encoded response to templates which would not be able to parse the response properly.

The correct order, then, is this:

[
    {"handler": "encode"},
    {"handler": "templates"},
    {"handler": "file_server"}
]

The request flows ⬇️ DOWN (encode -> templates -> file_server).

  1. First, encode will choose how to encode the response and wrap the response.
  2. Then, templates will wrap the response with a buffer.
  3. Finally, file_server will originate the content from a file.

The response flows ⬆️ UP (file_server -> templates -> encode):

  1. First, file_server will write the file to the response.
  2. That write will be buffered and then executed by templates.
  3. Lastly, the write from templates will flow into encode which will compress the stream.

If you think of routes in this way, it will be easy and even fun to solve the puzzle of writing correct routes.

Terminal

bool

If true, no more routes will be executed after this one.

MatcherSets

MatcherSets

decoded values

Handlers

[]MiddlewareHandler

No comment on field.
middleware

[]Middleware

No comment on field.

RouteList

RouteList is a list of server routes that can create a middleware chain.

Field name Field type Comment
type

[]Route

No comment on field.

Server

Server describes an HTTP server.

Field name Field type Comment
Listen

[]string

Socket addresses to which to bind listeners. Accepts network addresses that may include port ranges. Listener addresses must be unique; they cannot be repeated across all defined servers.

ListenerWrappersRaw

[]json.RawMessage

A list of listener wrapper modules, which can modify the behavior of the base listener. They are applied in the given order.

ReadTimeout

caddy.Duration

How long to allow a read from a client's upload. Setting this to a short, non-zero value can mitigate slowloris attacks, but may also affect legitimately slow clients.

ReadHeaderTimeout

caddy.Duration

ReadHeaderTimeout is like ReadTimeout but for request headers. Default is 1 minute.

WriteTimeout

caddy.Duration

WriteTimeout is how long to allow a write to a client. Note that setting this to a small value when serving large files may negatively affect legitimately slow clients.

IdleTimeout

caddy.Duration

IdleTimeout is the maximum time to wait for the next request when keep-alives are enabled. If zero, a default timeout of 5m is applied to help avoid resource exhaustion.

KeepAliveInterval

caddy.Duration

KeepAliveInterval is the interval at which TCP keepalive packets are sent to keep the connection alive at the TCP layer when no other data is being transmitted. The default is 15s.

MaxHeaderBytes

int

MaxHeaderBytes is the maximum size to parse from a client's HTTP request headers.

EnableFullDuplex

bool

Enable full-duplex communication for HTTP/1 requests. Only has an effect if Caddy was built with Go 1.21 or later.

For HTTP/1 requests, the Go HTTP server by default consumes any unread portion of the request body before beginning to write the response, preventing handlers from concurrently reading from the request and writing the response. Enabling this option disables this behavior and permits handlers to continue to read from the request while concurrently writing the response.

For HTTP/2 requests, the Go HTTP server always permits concurrent reads and responses, so this option has no effect.

Test thoroughly with your HTTP clients, as some older clients may not support full-duplex HTTP/1 which can cause them to deadlock. See https://github.com/golang/go/issues/57786 for more info.

TODO: This is an EXPERIMENTAL feature. Subject to change or removal.

Routes

RouteList

Routes describes how this server will handle requests. Routes are executed sequentially. First a route's matchers are evaluated, then its grouping. If it matches and has not been mutually-excluded by its grouping, then its handlers are executed sequentially. The sequence of invoked handlers comprises a compiled middleware chain that flows from each matching route and its handlers to the next.

By default, all unrouted requests receive a 200 OK response to indicate the server is working.

Errors

*HTTPErrorConfig

Errors is how this server will handle errors returned from any of the handlers in the primary routes. If the primary handler chain returns an error, the error along with its recommended status code are bubbled back up to the HTTP server which executes a separate error route, specified using this property. The error routes work exactly like the normal routes.

NamedRoutes

map[string]*Route

NamedRoutes describes a mapping of reusable routes that can be invoked by their name. This can be used to optimize memory usage when the same route is needed for many subroutes, by having the handlers and matchers be only provisioned once, but used from many places. These routes are not executed unless they are invoked from another route.

EXPERIMENTAL: Subject to change or removal.

TLSConnPolicies

caddytls.ConnectionPolicies

How to handle TLS connections. At least one policy is required to enable HTTPS on this server if automatic HTTPS is disabled or does not apply.

AutoHTTPS

*AutoHTTPSConfig

AutoHTTPS configures or disables automatic HTTPS within this server. HTTPS is enabled automatically and by default when qualifying names are present in a Host matcher and/or when the server is listening only on the HTTPS port.

StrictSNIHost

*bool

If true, will require that a request's Host header match the value of the ServerName sent by the client's TLS ClientHello; often a necessary safeguard when using TLS client authentication.

TrustedProxiesRaw

json.RawMessage

A module which provides a source of IP ranges, from which requests should be trusted. By default, no proxies are trusted.

On its own, this configuration will not do anything, but it can be used as a default set of ranges for handlers or matchers in routes to pick up, instead of needing to configure each of them. See the reverse_proxy handler for example, which uses this to trust sensitive incoming X-Forwarded-* headers.

ClientIPHeaders

[]string

The headers from which the client IP address could be read from. These will be considered in order, with the first good value being used as the client IP. By default, only X-Forwarded-For is considered.

This depends on trusted_proxies being configured and the request being validated as coming from a trusted proxy, otherwise the client IP will be set to the direct remote IP address.

TrustedProxiesStrict

int

If greater than zero, enables strict ClientIPHeaders (default X-Forwarded-For) parsing. If enabled, the ClientIPHeaders will be parsed from right to left, and the first value that is both valid and doesn't match the trusted proxy list will be used as client IP. If zero, the ClientIPHeaders will be parsed from left to right, and the first value that is a valid IP address will be used as client IP.

This depends on trusted_proxies being configured. This option is disabled by default.

Logs

*ServerLogConfig

Enables access logging and configures how access logs are handled in this server. To minimally enable access logs, simply set this to a non-null, empty struct.

Protocols

[]string

Protocols specifies which HTTP protocols to enable. Supported values are:

  • h1 (HTTP/1.1)
  • h2 (HTTP/2)
  • h2c (cleartext HTTP/2)
  • h3 (HTTP/3)

If enabling h2 or h2c, h1 must also be enabled; this is due to current limitations in the Go standard library.

HTTP/2 operates only over TLS (HTTPS). HTTP/3 opens a UDP socket to serve QUIC connections.

H2C operates over plain TCP if the client supports it; however, because this is not implemented by the Go standard library, other server options are not compatible and will not be applied to H2C requests. Do not enable this only to achieve maximum client compatibility. In practice, very few clients implement H2C, and even fewer require it. Enabling H2C can be useful for serving/proxying gRPC if encryption is not possible or desired.

We recommend for most users to simply let Caddy use the default settings.

Default: [h1 h2 h3]

ListenProtocols

[][]string

ListenProtocols overrides Protocols for each parallel address in Listen. A nil value or element indicates that Protocols will be used instead.

Metrics

*Metrics

If set, metrics observations will be enabled. This setting is EXPERIMENTAL and subject to change. DEPRECATED: Use the app-level metrics field.

name

string

No comment on field.
primaryHandlerChain

Handler

No comment on field.
errorHandlerChain

Handler

No comment on field.
listenerWrappers

[]caddy.ListenerWrapper

No comment on field.
listeners

[]net.Listener

No comment on field.
tlsApp

*caddytls.TLS

No comment on field.
events

*caddyevents.App

No comment on field.
logger

*zap.Logger

No comment on field.
accessLogger

*zap.Logger

No comment on field.
errorLogger

*zap.Logger

No comment on field.
traceLogger

*zap.Logger

No comment on field.
ctx

caddy.Context

No comment on field.
server

*http.Server

No comment on field.
h3server

*http3.Server

No comment on field.
h2listeners

[]*http2Listener

No comment on field.
addresses

[]caddy.NetworkAddress

No comment on field.
trustedProxies

IPRangeSource

No comment on field.
shutdownAt

time.Time

No comment on field.
shutdownAtMu

*sync.RWMutex

No comment on field.
connStateFuncs

[]func(net.Conn, http.ConnState)

registered callback functions

connContextFuncs

[]func(ctx context.Context, c net.Conn) context.Context

No comment on field.
onShutdownFuncs

[]func()

No comment on field.
onStopFuncs

[]func(context.Context) error

No comment on field.

ServerLogConfig

ServerLogConfig describes a server's logging configuration. If enabled without customization, all requests to this server are logged to the default logger; logger destinations may be customized per-request-host.

Field name Field type Comment
DefaultLoggerName

string

The default logger name for all logs emitted by this server for hostnames that are not in the logger_names map.

LoggerNames

map[string]StringArray

LoggerNames maps request hostnames to one or more custom logger names. For example, a mapping of "example.com": ["example"] would cause access logs from requests with a Host of example.com to be emitted by a logger named "http.log.access.example". If there are multiple logger names, then the log will be emitted to all of them. If the logger name is an empty, the default logger is used, i.e. the logger "http.log.access".

Keys must be hostnames (without ports), and may contain wildcards to match subdomains. The value is an array of logger names.

For backwards compatibility, if the value is a string, it is treated as a single-element array.

SkipHosts

[]string

By default, all requests to this server will be logged if access logging is enabled. This field lists the request hosts for which access logging should be disabled.

SkipUnmappedHosts

bool

If true, requests to any host not appearing in the logger_names map will not be logged.

ShouldLogCredentials

bool

If true, credentials that are otherwise omitted, will be logged. The definition of credentials is defined by https://fetch.spec.whatwg.org/#credentials, and this includes some request and response headers, i.e Cookie, Set-Cookie, Authorization, and Proxy-Authorization.

Trace

bool

Log each individual handler that is invoked. Requires that the log emit at DEBUG level.

NOTE: This may log the configuration of your HTTP handler modules; do not enable this in insecure contexts when there is sensitive data in the configuration.

EXPERIMENTAL: Subject to change or removal.

ShouldBufferFunc

ShouldBufferFunc is a function that returns true if the response should be buffered, given the pending HTTP status code and response headers.

Field name Field type Comment
type

func(status int, header http.Header) bool

No comment on field.

StaticError

StaticError implements a simple handler that returns an error. This handler returns an error value, but does not write a response. This is useful when you want the server to act as if an error occurred; for example, to invoke your custom error handling logic.

Since this handler does not write a response, the error information is for use by the server to know how to handle the error.

Field name Field type Comment
Error

string

The error message. Optional. Default is no error message.

StatusCode

WeakString

The recommended HTTP status code. Can be either an integer or a string if placeholders are needed. Optional. Default is 500.

StaticIPRange

StaticIPRange provides a static range of IP address prefixes (CIDRs).

Field name Field type Comment
Ranges

[]string

A static list of IP ranges (supports CIDR notation).

ranges

[]netip.Prefix

Holds the parsed CIDR ranges from Ranges.

StaticResponse

StaticResponse implements a simple responder for static responses.

Field name Field type Comment
StatusCode

WeakString

The HTTP status code to respond with. Can be an integer or, if needing to use a placeholder, a string.

If the status code is 103 (Early Hints), the response headers will be written to the client immediately, the body will be ignored, and the next handler will be invoked. This behavior is EXPERIMENTAL while RFC 8297 is a draft, and may be changed or removed.

Headers

http.Header

Header fields to set on the response; overwrites any existing header fields of the same names after normalization.

Body

string

The response body. If non-empty, the Content-Type header may be added automatically if it is not explicitly configured nor already set on the response; the default value is "text/plain; charset=utf-8" unless the body is a valid JSON object or array, in which case the value will be "application/json". Other than those common special cases the Content-Type header should be set explicitly if it is desired because MIME sniffing is disabled for safety.

Close

bool

If true, the server will close the client's connection after writing the response.

Abort

bool

Immediately and forcefully closes the connection without writing a response. Interrupts any other HTTP streams on the same connection.

StringArray

StringArray is a slices of strings, but also accepts a single string as a value when JSON unmarshaling, converting it to a slice of one string.

Field name Field type Comment
type

[]string

No comment on field.

Subroute

Subroute implements a handler that compiles and executes routes. This is useful for a batch of routes that all inherit the same matchers, or for multiple routes that should be treated as a single route.

You can also use subroutes to handle errors from its handlers. First the primary routes will be executed, and if they return an error, the errors routes will be executed; in that case, an error is only returned to the entry point at the server if there is an additional error returned from the errors routes.

Field name Field type Comment
Routes

RouteList

The primary list of routes to compile and execute.

Errors

*HTTPErrorConfig

If the primary routes return an error, error handling can be promoted to this configuration instead.

VarsMatcher

VarsMatcher is an HTTP request matcher which can match requests based on variables in the context or placeholder values. The key is the placeholder or name of the variable, and the values are possible values the variable can be in order to match (logical OR'ed).

If the key is surrounded by { } it is assumed to be a placeholder. Otherwise, it will be considered a variable name.

Placeholders in the keys are not expanded, but placeholders in the values are.

Field name Field type Comment
type

map[string][]string

No comment on field.

VarsMiddleware

VarsMiddleware is an HTTP middleware which sets variables to have values that can be used in the HTTP request handler chain. The primary way to access variables is with placeholders, which have the form: {http.vars.variable_name}, or with the vars and vars_regexp request matchers.

The key is the variable name, and the value is the value of the variable. Both the name and value may use or contain placeholders.

Field name Field type Comment
type

map[string]any

No comment on field.

WeakString

WeakString is a type that unmarshals any JSON value as a string literal, with the following exceptions:

  1. actual string values are decoded as strings; and
  2. null is decoded as empty string;

and provides methods for getting the value as various primitive types. However, using this type removes any type safety as far as deserializing JSON is concerned.

Field name Field type Comment
type

string

No comment on field.

MatchHost, MatchPath, MatchPathRE, MatchMethod, MatchQuery, MatchHeader, MatchHeaderRE, MatchProtocol, MatchTLS, MatchNot

This type doesn't have documentation.

Field name Field type Comment
type

[]string

No comment on field.
type

[]string

No comment on field.

MatchRegexp

No comment on field.
type

[]string

No comment on field.
type

url.Values

No comment on field.
type

http.Header

No comment on field.
type

map[string]*MatchRegexp

No comment on field.
type

string

No comment on field.
HandshakeComplete

*bool

Matches if the TLS handshake has completed. QUIC 0-RTT early data may arrive before the handshake completes. Generally, it is unsafe to replay these requests if they are not idempotent; additionally, the remote IP of early data packets can more easily be spoofed. It is conventional to respond with HTTP 425 Too Early if the request cannot risk being processed in this state.

MatcherSetsRaw

[]caddy.ModuleMap

No comment on field.
MatcherSets

[]MatcherSet

No comment on field.

acmeCapable

This type doesn't have documentation.

Field name Field type Comment
type

any

No comment on field.

celHTTPRequest

celHTTPRequest wraps an http.Request with ref.Val interface methods.

This type also implements the interpreter.Activation interface which drops allocation costs for CEL expression evaluations by roughly half.

Field name Field type Comment

*http.Request

No comment on field.

celPkixName

celPkixName wraps an pkix.Name with methods to satisfy the ref.Val interface.

Field name Field type Comment

*pkix.Name

No comment on field.

celTypeAdapter

celTypeAdapter can adapt our custom types to a CEL value.

connectionStateConn

This type doesn't have documentation.

Field name Field type Comment
type

any

No comment on field.

hijackedConn

used to track the size of hijacked response writers

Field name Field type Comment

net.Conn

No comment on field.
rr

*responseRecorder

No comment on field.

http2Listener

http2Listener wraps the listener to solve the following problems:

  1. server h2 natively without using h2c hack when listener handles tls connection but don't return *tls.Conn
  2. graceful shutdown. the shutdown logic is copied from stdlib http.Server, it's an extra maintenance burden but whatever, the shutdown logic maybe extracted to be used with h2c graceful shutdown. http2.Server supports graceful shutdown sending GO_AWAY frame to connected clients, but doesn't track connection status. It requires explicit call of http2.ConfigureServer

Field name Field type Comment
cnt

uint64

No comment on field.

net.Listener

No comment on field.
server

*http.Server

No comment on field.
h2server

*http2.Server

No comment on field.

httpMetrics

This type doesn't have documentation.

Field name Field type Comment
requestInFlight

*prometheus.GaugeVec

No comment on field.
requestCount

*prometheus.CounterVec

No comment on field.
requestErrors

*prometheus.CounterVec

No comment on field.
requestDuration

*prometheus.HistogramVec

No comment on field.
requestSize

*prometheus.HistogramVec

No comment on field.
responseSize

*prometheus.HistogramVec

No comment on field.
responseDuration

*prometheus.HistogramVec

No comment on field.

httpRedirectConn

This type doesn't have documentation.

Field name Field type Comment

net.Conn

No comment on field.
once

bool

No comment on field.
limit

int64

No comment on field.
r

*bufio.Reader

No comment on field.

httpRedirectListener

httpRedirectListener is listener that checks the first few bytes of the request when the server is intended to accept HTTPS requests, to respond to an HTTP request with a redirect.

Field name Field type Comment

net.Listener

No comment on field.
maxHeaderBytes

int64

No comment on field.

lengthReader

lengthReader is an io.ReadCloser that keeps track of the number of bytes read from the request body.

Field name Field type Comment
Source

io.ReadCloser

No comment on field.
Length

int

No comment on field.

matcherCELLibrary

matcherCELLibrary is a simplistic configurable cel.Library implementation.

Field name Field type Comment
envOptions

[]cel.EnvOption

No comment on field.
programOptions

[]cel.ProgramOption

No comment on field.

metricsInstrumentedHandler

This type doesn't have documentation.

Field name Field type Comment
handler

string

No comment on field.
mh

MiddlewareHandler

No comment on field.
metrics

*Metrics

No comment on field.

requestID

This type doesn't have documentation.

Field name Field type Comment
value

string

No comment on field.

responseRecorder

This type doesn't have documentation.

Field name Field type Comment

*ResponseWriterWrapper

No comment on field.
statusCode

int

No comment on field.
buf

*bytes.Buffer

No comment on field.
shouldBuffer

ShouldBufferFunc

No comment on field.
size

int

No comment on field.
wroteHeader

bool

No comment on field.
stream

bool

No comment on field.
readSize

*int

No comment on field.

tlsPlaceholderWrapper

tlsPlaceholderWrapper is a no-op listener wrapper that marks where the TLS listener should be in a chain of listener wrappers. It should only be used if another listener wrapper must be placed in front of the TLS handshake.

Functions

func CELMatcherDecorator

CELMatcherDecorator matches a call overload generated by a CEL macro that takes a single argument, and optimizes the implementation to precompile the matcher and return a function that references the precompiled and provisioned matcher.

Uses: errors.New, fmt.Errorf, interpreter.Interpretable, interpreter.InterpretableAttribute, interpreter.InterpretableCall, interpreter.InterpretableConst, interpreter.NamespacedAttribute, interpreter.NewCall, ref.Val, types.Bool, types.WrapErr.

func CELMatcherImpl

CELMatcherImpl creates a new cel.Library based on the following pieces of data:

  • macroName: the function name to be used within CEL. This will be a macro and not a function proper.
  • funcName: the function overload name generated by the CEL macro used to represent the matcher.
  • matcherDataTypes: the argument types to the macro.
  • fac: a matcherFactory implementation which converts from CEL constant values to a Matcher instance.

Note, macro names and function names must not collide with other macros or functions exposed within CEL expressions, or an error will be produced during the expression matcher plan time.

The existing CELMatcherImpl support methods are configured to support a limited set of function signatures. For strong type validation you may need to provide a custom macro which does a more detailed analysis of the CEL literal provided to the macro as an argument.

Uses: cel.BoolType, cel.CustomDecorator, cel.EnvOption, cel.Function, cel.ListType, cel.Macros, cel.ObjectType, cel.Overload, cel.ProgramOption, cel.SingletonBinaryBinding, cel.StringType, cel.Type, fmt.Errorf, parser.Macro, parser.NewGlobalMacro, parser.NewGlobalVarArgMacro.

func CELMatcherRuntimeFunction

CELMatcherRuntimeFunction creates a function binding for when the input to the matcher is dynamically resolved rather than a set of static constant values.

Uses: ref.Val, types.Bool, types.NewErr, types.WrapErr.

func CELValueToMapStrList

CELValueToMapStrList converts a CEL value to a map[string][]string

Earlier validation stages should guarantee that the value has this type at compile time, and that the runtime value type is map[string]any. The reason for the slight difference in value type is that CEL allows for map literals containing heterogeneous values, in this case string and list of string.

Uses: fmt.Errorf, ref.Val, reflect.TypeOf, types.String.

func CIDRExpressionToPrefix

CIDRExpressionToPrefix takes a string which could be either a CIDR expression or a single IP address, and returns a netip.Prefix.

Uses: fmt.Errorf, netip.ParseAddr, netip.ParsePrefix, netip.Prefix, netip.PrefixFrom, strings.Contains.

func CleanPath

CleanPath cleans path p according to path.Clean(), but only merges repeated slashes if collapseSlashes is true, and always preserves trailing slashes.

Uses: strings.Builder, strings.ReplaceAll.

func Error

Error is a convenient way for a Handler to populate the essential fields of a HandlerError. If err is itself a HandlerError, then any essential fields that are not set will be populated.

Uses: errors.As.

func GetVar

GetVar gets a value out of the context's variable table by key. If the key does not exist, the return value will be nil.

func NewMatcherCELLibrary

NewMatcherCELLibrary creates a matcherLibrary from option setes.

func NewResponseRecorder

NewResponseRecorder returns a new ResponseRecorder that can be used instead of a standard http.ResponseWriter. The recorder is useful for middlewares which need to buffer a response and potentially process its entire body before actually writing the response to the underlying writer. Of course, buffering the entire body has a memory overhead, but sometimes there is no way to avoid buffering the whole response, hence the existence of this type. Still, if at all practical, handlers should strive to stream responses by wrapping Write and WriteHeader methods instead of buffering whole response bodies.

Buffering is actually optional. The shouldBuffer function will be called just before the headers are written. If it returns true, the headers and body will be buffered by this recorder and not written to the underlying writer; if false, the headers will be written immediately and the body will be streamed out directly to the underlying writer. If shouldBuffer is nil, the response will never be buffered and will always be streamed directly to the writer.

You can know if shouldBuffer returned true by calling Buffered().

The provided buffer buf should be obtained from a pool for best performance (see the sync.Pool type).

Proper usage of a recorder looks like this:

rec := caddyhttp.NewResponseRecorder(w, buf, shouldBuffer)
err := next.ServeHTTP(rec, req)
if err != nil {
    return err
}
if !rec.Buffered() {
    return nil
}
// process the buffered response here

The header map is not buffered; i.e. the ResponseRecorder's Header() method returns the same header map of the underlying ResponseWriter. This is a crucial design decision to allow HTTP trailers to be flushed properly (https://github.com/caddyserver/caddy/issues/3236).

Once you are ready to write the response, there are two ways you can do it. The easier way is to have the recorder do it:

rec.WriteResponse()

This writes the recorded response headers as well as the buffered body. Or, you may wish to do it yourself, especially if you manipulated the buffered body. First you will need to write the headers with the recorded status code, then write the body (this example writes the recorder's body buffer, but you might have your own body to write instead):

w.WriteHeader(rec.Status())
io.Copy(w, rec.Buffer())

As a special case, 1xx responses are not buffered nor recorded because they are not the final response; they are passed through directly to the underlying ResponseWriter.

func NewTestReplacer

NewTestReplacer creates a replacer for an http.Request for use in tests that are not in this package

Uses: context.WithValue.

func ParseCaddyfileNestedMatcherSet

ParseCaddyfileNestedMatcher parses the Caddyfile tokens for a nested matcher set, and returns its raw module map value.

Uses: caddyfile.NewDispenser, caddyfile.Token, caddyfile.Unmarshaler, fmt.Errorf, json.Marshal.

func ParseNamedResponseMatcher

ParseNamedResponseMatcher parses the tokens of a named response matcher.

@name {
    header <field> [<value>]
    status <code...>
}

Or, single line syntax:

@name [header <field> [<value>]] | [status <code...>]

Uses: http.Header, strconv.Atoi, strings.HasSuffix.

func PrepareRequest

PrepareRequest fills the request r for use in a Caddy HTTP handler chain. w and s can be nil, but the handlers will lose response placeholders and access to the server.

Uses: context.WithValue, url.URL.

func PrivateRangesCIDR

PrivateRangesCIDR returns a list of private CIDR range strings, which can be used as a configuration shortcut. Note: this function is used at least by mholt/caddy-l4.

func RegisterNetworkHTTP3

RegisterNetworkHTTP3 registers a mapping from non-HTTP/3 network to HTTP/3 network. This should be called during init() and will panic if the network type is standard, reserved, or already registered.

EXPERIMENTAL: Subject to change.

Uses: strings.ToLower.

func SanitizedPathJoin

SanitizedPathJoin performs filepath.Join(root, reqPath) that is safe against directory traversal attacks. It uses logic similar to that in the Go standard library, specifically in the implementation of http.Dir. The root is assumed to be a trusted path, but reqPath is not; and the output will never be outside of root. The resulting path can be used with the local file system. If root is empty, the current directory is assumed. If the cleaned request path is deemed not local according to lexical processing (i.e. ignoring links), it will be rejected as unsafe and only the root will be returned.

Uses: filepath.FromSlash, filepath.IsLocal, filepath.Join, path.Clean, strings.HasSuffix.

func SetVar

SetVar sets a value in the context's variable table with the given key. It overwrites any previous value with the same key.

If the value is nil (note: non-nil interface with nil underlying value does not count) and the key exists in the table, the key+value will be deleted from the table.

func StatusCodeMatches

StatusCodeMatches returns true if a real HTTP status code matches the configured status code, which may be either a real HTTP status code or an integer representing a class of codes (e.g. 4 for all 4xx statuses).

func (*App) Provision

Provision sets up the app.

Uses: caddyevents.App, caddytls.TLS, cmp.Or, context.WithValue, fmt.Errorf, maps.Clone, sync.Once, sync.RWMutex, zap.String.

func (*App) Start

Start runs the app. It finishes automatic HTTPS if enabled, including management of certificates.

Uses: context.Context, context.WithValue, fmt.Errorf, h2c.NewHandler, http.Handler, http.Server, http2.ConfigureServer, http2.Server, net.Conn, net.ListenConfig, net.Listener, time.Duration, tls.Conn, tls.NewListener, zap.Bool, zap.DebugLevel, zap.NewStdLogAt, zap.String, zap.Strings.

func (*App) Stop

Stop gracefully shuts down the HTTP server.

Uses: context.Background, context.CancelFunc, context.WithTimeout, sync.WaitGroup, time.Duration, time.Now, time.Sleep, zap.Duration, zap.Error, zap.Int, zap.String, zap.Strings, zap.Time.

func (*App) Validate

Validate ensures the app's configuration is valid.

Uses: fmt.Errorf, net.SplitHostPort, strconv.FormatUint.

func (*ExtraLogFields) Add

Add adds a field to the list of extra fields to log.

func (*ExtraLogFields) Set

Set sets a field in the list of extra fields to log. If the field already exists, it is replaced.

func (*HTTPErrorConfig) WithError

WithError makes a shallow copy of r to add the error to its context, and sets placeholders on the request's replacer related to err. It returns the modified request which has the error information in its context and replacer. It overwrites any existing error values that are stored.

Uses: context.WithValue, http.StatusText.

func (*HTTPRedirectListenerWrapper) UnmarshalCaddyfile

func (*HTTPRedirectListenerWrapper) WrapListener

func (*Invoke) ServeHTTP

Uses: fmt.Errorf.

func (*MatchClientIP) Provision

Provision parses m's IP ranges, either from IP or CIDR expressions.

func (*MatchClientIP) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchExpression) Provision

Provision sets ups m.

Uses: cel.AnyType, cel.BoolType, cel.CustomTypeAdapter, cel.EnvOption, cel.EvalOptions, cel.Function, cel.Lib, cel.NewEnv, cel.OptOptimize, cel.Overload, cel.ProgramOption, cel.SingletonBinaryBinding, cel.StringType, cel.Type, cel.Variable, ext.Bindings, ext.Lists, ext.Math, ext.Strings, fmt.Errorf.

func (*MatchExpression) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

Uses: caddyfile.MatcherNameCtxKey, strings.Join.

func (*MatchExpression) UnmarshalJSON

UnmarshalJSON unmarshals m's expression.

Uses: json.Unmarshal.

func (*MatchHeader) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

Uses: http.Header, strings.HasPrefix.

func (*MatchHeaderRE) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

Uses: caddyfile.MatcherNameCtxKey.

func (*MatchHost) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchMethod) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchNot) Provision

Provision loads the matcher modules to be negated.

Uses: fmt.Errorf.

func (*MatchNot) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchNot) UnmarshalJSON

UnmarshalJSON satisfies json.Unmarshaler. It puts the JSON bytes directly into m's MatcherSetsRaw field.

Uses: json.Unmarshal.

func (*MatchPath) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchProtocol) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchQuery) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

Uses: strings.Cut, url.Values.

func (*MatchRegexp) Match

Match returns true if input matches the compiled regular expression in mre. It sets values on the replacer repl associated with capture groups, using the given scope (namespace).

Uses: strconv.Itoa.

func (*MatchRegexp) Provision

Provision compiles the regular expression.

Uses: fmt.Errorf, regexp.Compile.

func (*MatchRegexp) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

Uses: caddyfile.MatcherNameCtxKey.

func (*MatchRegexp) Validate

Validate ensures mre is set up correctly.

Uses: fmt.Errorf.

func (*MatchRemoteIP) Provision

Provision parses m's IP ranges, either from IP or CIDR expressions.

func (*MatchRemoteIP) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*MatchTLS) UnmarshalCaddyfile

UnmarshalCaddyfile parses Caddyfile tokens for this matcher. Syntax:

... tls [early_data]

EXPERIMENTAL SYNTAX: Subject to change.

func (*MatchVarsRE) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

Uses: caddyfile.MatcherNameCtxKey.

func (*MatcherSets) FromInterface

FromInterface fills ms from an 'any' value obtained from LoadModule.

Uses: fmt.Errorf.

func (*ResponseHandler) Provision

Provision sets up the routes in rh.

func (*ResponseWriterWrapper) Push

Push implements http.Pusher. It simply calls the underlying ResponseWriter's Push method if there is one, or returns ErrNotImplemented otherwise.

Uses: http.Pusher.

func (*ResponseWriterWrapper) ReadFrom

ReadFrom implements io.ReaderFrom. It retries to use io.ReaderFrom if available, then fallback to io.Copy. see: https://github.com/caddyserver/caddy/issues/6546

Uses: io.Copy, io.ReaderFrom.

func (*ResponseWriterWrapper) Unwrap

Unwrap returns the underlying ResponseWriter, necessary for http.ResponseController to work correctly.

func (*Route) Provision

Provision sets up both the matchers and handlers in the route.

func (*Route) ProvisionHandlers

ProvisionHandlers sets up all the handlers by loading the handler modules. Only call this method directly if you need to set up matchers and handlers separately without having to provision a second time; otherwise use Provision instead.

Uses: fmt.Errorf.

func (*Route) ProvisionMatchers

ProvisionMatchers sets up all the matchers by loading the matcher modules. Only call this method directly if you need to set up matchers and handlers separately without having to provision a second time; otherwise use Provision instead.

Uses: fmt.Errorf.

func (*Server) Listeners

Listeners returns the server's listeners. These are active listeners, so calling Accept() or Close() on them will probably break things. They are made available here for read-only purposes (e.g. Addr()) and for type-asserting for purposes where you know what you're doing.

EXPERIMENTAL: Subject to change or removal.

func (*Server) Name

Name returns the server's name.

func (*Server) RegisterConnContext

RegisterConnContext registers f to be invoked as part of s.ConnContext.

func (*Server) RegisterConnState

RegisterConnState registers f to be invoked on s.ConnState.

func (*Server) RegisterOnShutdown

RegisterOnShutdown registers f to be invoked when the server begins to shut down.

func (*Server) RegisterOnStop

RegisterOnStop registers f to be invoked after the server has shut down completely.

EXPERIMENTAL: Subject to change or removal.

func (*Server) ServeHTTP

ServeHTTP is the entry point for all HTTP requests.

Uses: http.NewResponseController, http.Request, http.StatusInternalServerError, http.StatusMethodNotAllowed, net.Conn, time.Duration, time.Now, time.Since, tls.ConnectionState, zap.Duration, zap.Error, zap.Logger, zap.Namespace, zap.Object, zap.String, zapcore.DebugLevel, zapcore.ErrorLevel, zapcore.Field, zapcore.WarnLevel.

func (*StaticError) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:

error [<matcher>] <status>|<message> [<status>] {
    message <text>
}

If there is just one argument (other than the matcher), it is considered to be a status code if it's a valid positive integer of 3 digits.

Uses: strconv.Atoi.

func (*StaticIPRange) GetIPRanges

func (*StaticIPRange) Provision

func (*StaticIPRange) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*StaticResponse) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:

respond [<matcher>] <status>|<body> [<status>] {
    body <text>
    close
}

If there is just one argument (other than the matcher), it is considered to be a status code if it's a valid positive integer of 3 digits.

Uses: strconv.Atoi.

func (*StringArray) UnmarshalJSON

UnmarshalJSON satisfies json.Unmarshaler.

Uses: errors.New, json.Unmarshal.

func (*Subroute) Provision

Provision sets up subrouting.

Uses: fmt.Errorf.

func (*Subroute) ServeHTTP

func (*VarsMatcher) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

func (*VarsMiddleware) UnmarshalCaddyfile

UnmarshalCaddyfile implements caddyfile.Unmarshaler. Syntax:

vars [<name> <val>] {
    <name> <val>
    ...
}

func (*WeakString) UnmarshalJSON

UnmarshalJSON satisfies json.Unmarshaler according to this type's documentation.

Uses: bytes.Equal, io.EOF, json.Unmarshal.

func (*hijackedConn) Read

func (*hijackedConn) ReadFrom

Uses: io.Copy.

func (*hijackedConn) Write

func (*hijackedConn) WriteTo

Uses: io.Copy.

func (*http2Listener) Accept

Uses: http2.NextProtoTLS.

func (*http2Listener) Shutdown

Uses: atomic.LoadUint64, time.Duration, time.Millisecond, time.NewTimer, weakrand.Intn.

func (*httpRedirectConn) Read

Read tries to peek at the first few bytes of the request, and if we get an error reading the headers, and that error was due to the bytes looking like an HTTP request, then we perform a HTTP->HTTPS redirect on the same port as the original connection.

Uses: bytes.NewReader, fmt.Errorf, http.Header, http.ReadRequest, http.Response, io.LimitReader, io.MultiReader.

func (*httpRedirectListener) Accept

Accept waits for and returns the next connection to the listener, wrapping it with a httpRedirectConn.

Uses: bufio.NewReader.

func (*lengthReader) Close

func (*lengthReader) Read

func (*matcherCELLibrary) CompileOptions

func (*matcherCELLibrary) ProgramOptions

func (*metricsInstrumentedHandler) ServeHTTP

Uses: errors.As, http.Header, metrics.SanitizeCode, metrics.SanitizeMethod, prometheus.Labels, strings.ToLower, time.Now, time.Since.

func (*requestID) String

Lazy generates UUID string or return cached value if present

Uses: uuid.NewRandom.

func (*responseRecorder) Buffer

Buffer returns the body buffer that rr was created with. You should still have your original pointer, though.

func (*responseRecorder) Buffered

Buffered returns whether rr has decided to buffer the response.

func (*responseRecorder) FlushError

FlushError will suppress actual flushing if the response is buffered. See: https://github.com/caddyserver/caddy/issues/6144

Uses: http.NewResponseController.

func (*responseRecorder) Hijack

Uses: bytes.NewReader, http.NewResponseController, io.MultiReader.

func (*responseRecorder) ReadFrom

Uses: http.StatusOK.

func (*responseRecorder) Size

Size returns the number of bytes written, not including the response headers.

func (*responseRecorder) Status

Status returns the status code that was written, if any.

func (*responseRecorder) Write

Uses: http.StatusOK.

func (*responseRecorder) WriteHeader

WriteHeader writes the headers with statusCode to the wrapped ResponseWriter unless the response is to be buffered instead. 1xx responses are never buffered.

func (*responseRecorder) WriteResponse

Uses: http.StatusOK, io.Copy.

func (App) CaddyModule

CaddyModule returns the Caddy module information.

func (HTTPRedirectListenerWrapper) CaddyModule

func (HandlerError) Error

Uses: fmt.Sprintf, strings.TrimSpace.

func (HandlerError) Unwrap

Unwrap returns the underlying error value. See the errors package for info.

func (HandlerFunc) ServeHTTP

ServeHTTP implements the Handler interface.

func (Invoke) CaddyModule

CaddyModule returns the Caddy module information.

func (LoggableHTTPHeader) MarshalLogObject

MarshalLogObject satisfies the zapcore.ObjectMarshaler interface.

Uses: strings.ToLower.

func (LoggableHTTPRequest) MarshalLogObject

MarshalLogObject satisfies the zapcore.ObjectMarshaler interface.

Uses: net.SplitHostPort.

func (LoggableStringArray) MarshalLogArray

MarshalLogArray satisfies the zapcore.ArrayMarshaler interface.

func (LoggableTLSConnState) MarshalLogObject

MarshalLogObject satisfies the zapcore.ObjectMarshaler interface.

func (MatchClientIP) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression client_ip('192.168.0.0/16', '172.16.0.0/12', '10.0.0.0/8')

Uses: cel.ListType, cel.StringType, cel.Type, ref.Val, reflect.TypeOf.

func (MatchClientIP) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchClientIP) Match

Match returns true if r matches m.

func (MatchClientIP) MatchWithError

MatchWithError returns true if r matches m.

Uses: fmt.Errorf, http.StatusTooEarly, zap.Error, zap.String.

func (MatchExpression) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchExpression) MarshalJSON

MarshalJSON marshals m's expression.

Uses: json.Marshal.

func (MatchExpression) Match

Match returns true if r matches m.

func (MatchExpression) MatchWithError

MatchWithError returns true if r matches m.

Uses: zap.Error.

func (MatchHeader) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression header({'content-type': 'image/png'})
expression header({'foo': ['bar', 'baz']}) // match bar or baz

Uses: cel.Type, http.Header, ref.Val.

func (MatchHeader) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchHeader) Match

Match returns true if r matches m.

func (MatchHeader) MatchWithError

MatchWithError returns true if r matches m.

Uses: http.Header.

func (MatchHeaderRE) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression header_regexp('foo', 'Field', 'fo+')

Uses: cel.StringType, cel.Type, ref.Val, reflect.TypeOf.

func (MatchHeaderRE) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchHeaderRE) Match

Match returns true if r matches m.

func (MatchHeaderRE) MatchWithError

MatchWithError returns true if r matches m.

func (MatchHeaderRE) Provision

Provision compiles m's regular expressions.

func (MatchHeaderRE) Validate

Validate validates m's regular expressions.

func (MatchHost) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression host('localhost')

Uses: cel.ListType, cel.StringType, cel.Type, ref.Val, reflect.TypeOf.

func (MatchHost) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchHost) Match

Match returns true if r matches m.

func (MatchHost) MatchWithError

MatchWithError returns true if r matches m.

Uses: net.SplitHostPort, sort.Search, strings.Contains, strings.EqualFold, strings.Split, strings.TrimPrefix, strings.TrimSuffix.

func (MatchHost) Provision

Provision sets up and validates m, including making it more efficient for large lists.

Uses: fmt.Errorf, idna.ToASCII, sort.Slice, strings.ToLower.

func (MatchMethod) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression method('PUT', 'POST')

Uses: cel.ListType, cel.StringType, cel.Type, ref.Val, reflect.TypeOf.

func (MatchMethod) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchMethod) Match

Match returns true if r matches m.

func (MatchMethod) MatchWithError

MatchWithError returns true if r matches m.

Uses: slices.Contains.

func (MatchNot) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchNot) MarshalJSON

MarshalJSON satisfies json.Marshaler by marshaling m's raw matcher sets.

Uses: json.Marshal.

func (MatchNot) Match

Match returns true if r matches m. Since this matcher negates the embedded matchers, false is returned if any of its matcher sets return true.

func (MatchNot) MatchWithError

MatchWithError returns true if r matches m. Since this matcher negates the embedded matchers, false is returned if any of its matcher sets return true.

func (MatchPath) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression path('*substring*', '*suffix')

Uses: cel.ListType, cel.StringType, cel.Type, ref.Val, reflect.TypeOf.

func (MatchPath) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchPath) Match

Match returns true if r matches m.

func (MatchPath) MatchWithError

MatchWithError returns true if r matches m.

Uses: path.Match, runtime.GOOS, strings.Contains, strings.Count, strings.HasPrefix, strings.HasSuffix, strings.ToLower, strings.TrimRight.

func (MatchPath) Provision

Provision lower-cases the paths in m to ensure case-insensitive matching.

Uses: strings.ToLower.

func (MatchPathRE) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression path_regexp('^/bar')

Uses: cel.StringType, cel.Type, ref.Val, reflect.TypeOf, types.String.

func (MatchPathRE) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchPathRE) Match

Match returns true if r matches m.

func (MatchPathRE) MatchWithError

MatchWithError returns true if r matches m.

func (MatchProtocol) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression protocol('https')

Uses: cel.StringType, cel.Type, errors.New, ref.Val, strings.ToLower, types.String.

func (MatchProtocol) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchProtocol) Match

Match returns true if r matches m.

func (MatchProtocol) MatchWithError

MatchWithError returns true if r matches m.

Uses: strings.HasPrefix.

func (MatchQuery) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression query({'sort': 'asc'}) || query({'foo': ['*bar*', 'baz']})

Uses: cel.Type, ref.Val, url.Values.

func (MatchQuery) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchQuery) Match

Match returns true if r matches m. An empty m matches an empty query string.

func (MatchQuery) MatchWithError

MatchWithError returns true if r matches m. An empty m matches an empty query string.

Uses: slices.Contains, url.ParseQuery.

func (MatchRemoteIP) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression remote_ip('192.168.0.0/16', '172.16.0.0/12', '10.0.0.0/8')

Uses: cel.ListType, cel.StringType, cel.Type, errors.New, ref.Val, reflect.TypeOf.

func (MatchRemoteIP) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchRemoteIP) Match

Match returns true if r matches m.

func (MatchRemoteIP) MatchWithError

MatchWithError returns true if r matches m.

Uses: fmt.Errorf, http.StatusTooEarly, zap.Error, zap.String, zapcore.DebugLevel, zapcore.ErrorLevel.

func (MatchTLS) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchTLS) Match

Match returns true if r matches m.

func (MatchTLS) MatchWithError

MatchWithError returns true if r matches m.

func (MatchVarsRE) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression vars_regexp('foo', '{magic_number}', '[0-9]+')
expression vars_regexp('{magic_number}', '[0-9]+')

Uses: cel.StringType, cel.Type, ref.Val, reflect.TypeOf.

func (MatchVarsRE) CaddyModule

CaddyModule returns the Caddy module information.

func (MatchVarsRE) Match

Match returns true if r matches m.

func (MatchVarsRE) MatchWithError

MatchWithError returns true if r matches m.

Uses: fmt.Sprintf, fmt.Stringer, strings.Count, strings.HasPrefix, strings.HasSuffix, strings.Trim.

func (MatchVarsRE) Provision

Provision compiles m's regular expressions.

func (MatchVarsRE) Validate

Validate validates m's regular expressions.

func (MatcherSet) Match

Match returns true if the request matches all matchers in mset or if there are no matchers.

func (MatcherSet) MatchWithError

MatchWithError returns true if r matches m.

Uses: fmt.Errorf.

func (MatcherSets) AnyMatch

AnyMatch returns true if req matches any of the matcher sets in ms or if there are no matchers, in which case the request always matches.

Deprecated: Use AnyMatchWithError instead.

func (MatcherSets) AnyMatchWithError

AnyMatchWithError returns true if req matches any of the matcher sets in ms or if there are no matchers, in which case the request always matches. If any matcher returns an error, we cut short and return the error.

func (MatcherSets) String

TODO: Is this used?

Uses: fmt.Sprintf.

func (ResponseMatcher) Match

Match returns true if the given statusCode and hdr match rm.

func (Route) Compile

Compile prepares a middleware chain from the route list. This should only be done once during the request, just before the middleware chain is executed.

func (Route) Empty

Empty returns true if the route has all zero/default values.

func (Route) String

Uses: fmt.Sprintf.

func (RouteList) Compile

Compile prepares a middleware chain from the route list. This should only be done either once during provisioning for top-level routes, or on each request just before the middleware chain is executed for subroutes.

func (RouteList) Provision

Provision sets up both the matchers and handlers in the routes.

func (RouteList) ProvisionHandlers

ProvisionHandlers sets up all the handlers by loading the handler modules. Only call this method directly if you need to set up matchers and handlers separately without having to provision a second time; otherwise use Provision instead.

Uses: fmt.Errorf.

func (RouteList) ProvisionMatchers

ProvisionMatchers sets up all the matchers by loading the matcher modules. Only call this method directly if you need to set up matchers and handlers separately without having to provision a second time; otherwise use Provision instead.

Uses: fmt.Errorf.

func (StaticError) CaddyModule

CaddyModule returns the Caddy module information.

func (StaticError) ServeHTTP

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

func (StaticIPRange) CaddyModule

CaddyModule returns the Caddy module information.

func (StaticResponse) CaddyModule

CaddyModule returns the Caddy module information.

func (StaticResponse) ServeHTTP

Uses: fmt.Fprint, http.ErrAbortHandler, http.StatusEarlyHints, http.StatusInternalServerError, http.StatusOK, json.Valid, strconv.Atoi, strings.TrimSpace, textproto.CanonicalMIMEHeaderKey.

func (Subroute) CaddyModule

CaddyModule returns the Caddy module information.

func (VarsMatcher) CELLibrary

CELLibrary produces options that expose this matcher for use in CEL expression matchers.

Example:

expression vars({'{magic_number}': ['3', '5']})
expression vars({'{foo}': 'single_value'})

Uses: cel.Type, ref.Val.

func (VarsMatcher) CaddyModule

CaddyModule returns the Caddy module information.

func (VarsMatcher) Match

Match matches a request based on variables in the context, or placeholders if the key is not a variable.

func (VarsMatcher) MatchWithError

MatchWithError returns true if r matches m.

Uses: fmt.Sprintf, fmt.Stringer, strings.Count, strings.HasPrefix, strings.HasSuffix, strings.Trim.

func (VarsMiddleware) CaddyModule

CaddyModule returns the Caddy module information.

func (VarsMiddleware) ServeHTTP

func (WeakString) Bool

Bool returns ws as a boolean. If ws is not a boolean, false is returned.

func (WeakString) Float64

Float64 returns ws as a float64. If ws is not a float value, the zero value is returned.

Uses: strconv.ParseFloat.

func (WeakString) Int

Int returns ws as an integer. If ws is not an integer, 0 is returned.

Uses: strconv.Atoi.

func (WeakString) MarshalJSON

MarshalJSON marshals was a boolean if true or false, a number if an integer, or a string otherwise.

Uses: json.Marshal, strconv.Atoi.

func (WeakString) String

String returns ws as a string.

func (celHTTPRequest) ConvertToNative

func (celHTTPRequest) ConvertToType

func (celHTTPRequest) Equal

Uses: types.Bool, types.ValOrErr.

func (celHTTPRequest) Parent

func (celHTTPRequest) ResolveName

func (celHTTPRequest) Type

func (celHTTPRequest) Value

func (celPkixName) ConvertToNative

func (celPkixName) ConvertToType

Uses: types.String.

func (celPkixName) Equal

Uses: types.Bool, types.ValOrErr.

func (celPkixName) Type

func (celPkixName) Value

func (celTypeAdapter) NativeToValue

Uses: pkix.Name, time.Time, types.DefaultTypeAdapter, types.Timestamp, types.WrapErr.

func (tlsPlaceholderWrapper) CaddyModule

func (tlsPlaceholderWrapper) UnmarshalCaddyfile

func (tlsPlaceholderWrapper) WrapListener

Private functions

func addHTTPVarsToReplacer

References: bytes.Buffer, http.LocalAddrContextKey, http.Request, io.Copy, io.NopCloser, net.Addr, net.SplitHostPort, netip.ParseAddr, path.Base, path.Ext, path.Split, strconv.Atoi, strings.Cut, strings.EqualFold, strings.HasPrefix, strings.Index, strings.Join, strings.Split, strings.TrimSuffix, textproto.CanonicalMIMEHeaderKey, time.Now, time.Since, time.Time, time.Until, zap.String.

func buildHTTPServer

References: bytes.Buffer, caddyconfig.JSONModuleObject, fmt.Sprintf, json.RawMessage, template.New, time.Second.

func celMatcherJSONMacroExpander

celMatcherJSONMacroExpander validates that the macro is called a single map literal argument.

The following function call is returned: <funcName>(request, arg)

References: ast.CallKind, ast.ComprehensionKind, ast.Expr, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, cel.MacroExprFactory, common.Error, fmt.Sprintf.

func celMatcherStringListMacroExpander

celMatcherStringListMacroExpander validates that the macro is called with a variable number of string arguments (at least one).

The arguments are collected into a single list argument the following function call returned: <funcName>(request, [args])

References: ast.Expr, cel.MacroExprFactory, common.Error.

func celMatcherStringMacroExpander

celMatcherStringMacroExpander validates that the macro is called a single string argument.

The following function call is returned: <funcName>(request, arg)

References: ast.Expr, cel.MacroExprFactory, common.Error.

func cleanPath

cleanPath does path.Clean(p) but preserves any trailing slash.

References: path.Clean, strings.HasSuffix.

func cloneURL

cloneURL makes a copy of r.URL and returns a new value that doesn't reference the original.

References: url.Userinfo.

func cmdRespond

References: caddyconfig.JSON, fmt.Errorf, fmt.Printf, fmt.Sprintf, http.Header, io.ReadAll, os.Args, os.ModeNamedPipe, os.Stdin, slices.Contains, strconv.Atoi, strings.Cut, strings.TrimSpace, zap.DebugLevel.

func computeApproximateRequestSize

taken from https://github.com/prometheus/client_golang/blob/6007b2b5cae01203111de55f753e76d8dac1f529/prometheus/promhttp/instrument_server.go#L298

func determineTrustedProxy

determineTrustedProxy parses the remote IP address of the request, and determines (if the server configured it) if the client is a trusted proxy. If trusted, also returns the real client IP if possible.

References: net.SplitHostPort, netip.ParseAddr, strings.Cut.

func errLogValues

errLogValues inspects err and returns the status code to use, the error log message, and any extra fields. If err is a HandlerError, the returned values will have richer information.

References: errors.As, http.StatusInternalServerError, zap.Error, zap.Int, zap.String, zapcore.Field.

func firstBytesLookLikeHTTP

firstBytesLookLikeHTTP reports whether a TLS record header looks like it might've been a misdirected plaintext HTTP request.

func getHTTP3Network

References: fmt.Errorf, strings.ToLower.

func getHeaderFieldVals

getHeaderFieldVals returns the field values for the given fieldName from input. The host parameter should be obtained from the http.Request.Host field, and the transferEncoding from http.Request.TransferEncoding, since net/http removes them from the header map.

References: textproto.CanonicalMIMEHeaderKey.

func getReqTLSReplacement

References: base64.StdEncoding, caddytls.ProtocolName, fmt.Sprintf, net.IP, pem.Block, pem.EncodeToMemory, sha256.Sum256, strconv.Atoi, strings.HasPrefix, strings.HasSuffix, strings.ToLower, tls.CipherSuiteName, url.URL.

func getTLSPeerCert

getTLSPeerCert retrieves the first peer certificate from a TLS session. Returns nil if no peer cert is in use.

func init

func initHTTPMetrics

References: promauto.With, prometheus.CounterOpts, prometheus.DefBuckets, prometheus.ExponentialBuckets, prometheus.GaugeOpts, prometheus.HistogramOpts.

func isCELCaddyPlaceholderCall

isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call.

References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind.

func isCELConcatCall

isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or other concat call arguments.

References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, operators.Add.

func isCELStringExpr

isCELStringExpr indicates whether the expression is a supported string expression

func isCELStringListLiteral

isCELStringListLiteral returns whether the expression resolves to a list literal containing only string constants or a placeholder call.

References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind.

func isCELStringLiteral

isCELStringLiteral returns whether the expression is a CEL string literal.

References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, types.StringType.

func isTailscaleDomain

References: strings.HasSuffix, strings.ToLower.

func isTrustedClientIP

isTrustedClientIP returns true if the given IP address is in the list of trusted IP ranges.

References: netip.Prefix, slices.ContainsFunc.

func marshalPublicKey

marshalPublicKey returns the byte encoding of pubKey.

References: asn1.Marshal, ecdsa.PublicKey, ed25519.PublicKey, fmt.Errorf, rsa.PublicKey.

func matchHeaders

matchHeaders returns true if input matches the criteria in against without regex. The host parameter should be obtained from the http.Request.Host field since net/http removes it from the header map.

References: strings.Contains, strings.HasPrefix, strings.HasSuffix.

func matchIPByCidrZones

func newMetricsInstrumentedHandler

func originalRequest

originalRequest returns a partial, shallow copy of req, including: req.Method, deep copy of req.URL (into the urlCopy parameter, which should be on the stack), req.RequestURI, and req.RemoteAddr. Notably, headers are not copied. This function is designed to be very fast and efficient, and useful primarily for read-only/logging purposes.

References: http.Request.

func parseIPZoneFromString

References: net.SplitHostPort, netip.IPv4Unspecified, netip.ParseAddr, strings.Contains, strings.Split.

func provisionCidrsZonesFromRanges

References: fmt.Errorf, netip.ParseAddr, netip.ParsePrefix, netip.Prefix, netip.PrefixFrom, strings.Contains, strings.Split.

func randString

randString returns a string of n random characters. It is not even remotely secure OR a proper distribution. But it's good enough for some things. It excludes certain confusing characters like I, l, 1, 0, O, etc. If sameCase is true, then uppercase letters are excluded.

References: weakrand.Int63.

func serverNameFromContext

serverNameFromContext extracts the current server name from the context. Returns "UNKNOWN" if none is available (should probably never happen).

func strictUntrustedClientIp

strictUntrustedClientIp iterates through the list of client IP headers, parses them from right-to-left, and returns the first valid IP address that is untrusted. If no valid IP address is found, then the direct remote address is returned.

References: net.SplitHostPort, netip.ParseAddr, strings.Cut, strings.Join, strings.Split, strings.TrimSpace.

func trace

References: fmt.Sprintf, path.Base, runtime.Caller, runtime.FuncForPC.

func trustedRealClientIP

trustedRealClientIP finds the client IP from the request assuming it is from a trusted client. If there is no client IP headers, then the direct remote address is returned. If there are client IP headers, then the first value from those headers is used.

References: net.SplitHostPort, netip.ParseAddr, strings.Cut, strings.Join, strings.Split, strings.TrimSpace.

func wrapMiddleware

wrapMiddleware wraps mh such that it can be correctly appended to a list of middleware in preparation for compiling into a handler chain. We can't do this inline inside a loop, because it relies on a reference to mh not changing until the execution of its handler (which is deferred by multiple func closures). In other words, we need to pull this particular MiddlewareHandler pointer into its own stack frame to preserve it so it won't be overwritten in future loop iterations.

References: http.Request, http.ResponseWriter.

func wrapRoute

wrapRoute wraps route with a middleware and handler so that it can be chained in and defer evaluation of its matchers to request-time. Like wrapMiddleware, it is vital that this wrapping takes place in its own stack frame so as to not overwrite the reference to the intended route by looping and changing the reference each time.

References: http.Request, http.ResponseWriter.

func automaticHTTPSPhase1

automaticHTTPSPhase1 provisions all route matchers, determines which domain names found in the routes qualify for automatic HTTPS, and sets up HTTP->HTTPS redirects. This phase must occur at the beginning of provisioning, because it may add routes and even servers to the app, which still need to be set up with the rest of them during provisioning.

References: caddytls.ConnectionPolicies, caddytls.ConnectionPolicy, caddytls.InternalIssuer, certmagic.SubjectIsIP, certmagic.SubjectQualifiesForCert, certmagic.SubjectQualifiesForPublicCert, fmt.Errorf, slices.Contains, strings.Contains, strings.Count, strings.Trim, zap.Int, zap.Reflect, zap.String.

func automaticHTTPSPhase2

automaticHTTPSPhase2 begins certificate management for all names in the qualifying domain set for each server. This phase must occur after provisioning and at the end of app start, after all the servers have been started. Doing this last ensures that there won't be any race for listeners on the HTTP or HTTPS ports when management is async (if CertMagic's solvers bind to those ports first, then our servers would fail to bind to them, which would be bad, since CertMagic's bindings are temporary and don't serve the user's sites!).

References: fmt.Errorf, zap.Strings.

func createAutomationPolicies

createAutomationPolicies ensures that automated certificates for this app are managed properly. This adds up to two automation policies: one for the public names, and one for the internal names. If a catch-all automation policy exists, it will be shallow-copied and used as the base for the new ones (this is important for preserving behavior the user intends to be "defaults").

References: caddytls.ACMEIssuer, caddytls.AutomationConfig, caddytls.AutomationPolicy, caddytls.DefaultIssuersProvisioned, caddytls.InternalIssuer, caddytls.Tailscale, certmagic.Issuer, certmagic.Manager, fmt.Errorf.

func fillInACMEIssuer

fillInACMEIssuer fills in default values into acmeIssuer that are defined in app; these values at time of writing are just app.HTTPPort and app.HTTPSPort, which are used by ACMEIssuer. Sure, we could just use the global/CertMagic defaults, but if a user has configured those ports in the HTTP app, it makes sense to use them in the TLS app too, even if they forgot (or were too lazy, like me) to set it in each automation policy that uses it -- this just makes things a little less tedious for the user, so they don't have to repeat those ports in potentially many places. This function never steps on existing config values. If any changes are made, acmeIssuer is reprovisioned. acmeIssuer must not be nil.

References: caddytls.ChallengesConfig, caddytls.HTTPChallengeConfig, caddytls.TLSALPNChallengeConfig.

func httpPort

func httpsPort

func makeRedirRoute

References: http.Header, http.StatusPermanentRedirect, strconv.Itoa.

func configureServer

configureServer applies/binds the registered callback functions to the server.

References: context.Context, http.ConnState, net.Conn.

func enforcementHandler

enforcementHandler is an implicit middleware which performs standard checks before executing the HTTP middleware chain.

References: fmt.Errorf, http.StatusMisdirectedRequest, net.SplitHostPort, strings.EqualFold.

func findLastRouteWithHostMatcher

findLastRouteWithHostMatcher returns the index of the last route in the server which has a host matcher. Used during Automatic HTTPS to determine where to insert the HTTP->HTTPS redirect route, such that it is after any other host matcher but before any "catch-all" route without a host matcher.

func hasListenerAddress

hasListenerAddress returns true if s has a listener at the given address fullAddr. Currently, fullAddr must represent exactly one socket address (port ranges are not supported)

References: runtime.GOOS.

func hasTLSClientAuth

References: caddytls.ConnectionPolicy, slices.ContainsFunc.

func listenersUseAnyPortOtherThan

listenersUseAnyPortOtherThan returns true if there are any listeners in s that use a port which is not otherPort.

func logRequest

logRequest logs the request to access logs, unless skipped.

References: zap.Duration, zap.Int, zap.Logger, zap.Object, zap.String, zapcore.ErrorLevel, zapcore.Field, zapcore.InfoLevel.

func logTrace

logTrace will log that this middleware handler is being invoked. It emits at DEBUG level.

References: zap.Any, zapcore.DebugLevel.

func protocol

protocol returns true if the protocol proto is configured/enabled.

References: slices.Contains.

func serveHTTP3

serveHTTP3 creates a QUIC listener, configures an HTTP/3 server if not already done, and then uses that server to serve HTTP/3 over the listener, with Server s as the handler.

References: fmt.Errorf, http3.Server, net.ListenConfig, qlog.DefaultConnectionTracer, time.Duration.

func shouldLogRequest

shouldLogRequest returns true if this request should be logged.

References: certmagic.MatchWildcard, net.SplitHostPort.

func wrapPrimaryRoute

wrapPrimaryRoute wraps stack (a compiled middleware handler chain) in s.enforcementHandler which performs crucial security checks, etc.

References: http.Request, http.ResponseWriter.

func clone

func updateReadSize

func runHook

func serveHttp2

References: atomic.AddUint64, context.Background, http.StateClosed, http.StateNew, http2.ServeConnOpts.

func setReadSize

Private interface so it can only be used in this package #TODO: maybe export it later

func caddyPlaceholderFunc

caddyPlaceholderFunc implements the custom CEL function that accesses the Replacer on a request and gets values from it.

References: types.NewErr, types.String.

func fuzzy

fuzzy returns true if the given hostname h is not a specific hostname, e.g. has placeholders or wildcards.

References: strings.ContainsAny.

func large

large returns true if m is considered to be large. Optimizing the matcher for smaller lists has diminishing returns. See related benchmark function in test file to conduct experiments.

func matchPatternWithEscapeSequence

References: path.Match, strings.Builder, strings.IndexByte, strings.ReplaceAll, strings.ToLower, url.PathUnescape.

func matchStatusCode

func getLoggerHosts

References: strings.Join, strings.Split.

func wrapLogger

wrapLogger wraps logger in one or more logger named according to user preferences for the given host.

References: net.SplitHostPort, zap.Logger.


Tests

Files: 9. Third party imports: 4. Imports from organisation: 0. Tests: 44. Benchmarks: 8.

Vars

Types

baseRespWriter

a barebones http.ResponseWriter mock

Field name Field type Comment
type

[]byte

No comment on field.

middlewareHandlerFunc

This type doesn't have documentation.

Field name Field type Comment
type

func(http.ResponseWriter, *http.Request, Handler) error

No comment on field.

nopSyncer

This type doesn't have documentation.

Field name Field type Comment
type

writeFunc

No comment on field.

readFromRespWriter

an http.ResponseWriter mock that supports ReadFrom

Field name Field type Comment

baseRespWriter

No comment on field.
called

bool

No comment on field.

responseWriterSpy

This type doesn't have documentation.

Field name Field type Comment
type

any

No comment on field.

writeFunc

This type doesn't have documentation.

Field name Field type Comment
type

func(p []byte) (int, error)

No comment on field.

Test functions

TestCleanPath

TestHTTPVarReplacement

References: context.WithValue, http.LocalAddrContextKey, http.MethodGet, http.NewRequest, httptest.NewRecorder, net.ResolveTCPAddr, pem.Decode, tls.ConnectionState, tls.TLS_AES_256_GCM_SHA384, tls.VersionTLS13, x509.Certificate, x509.ParseCertificate.

TestHeaderMatcher

References: context.WithValue, http.Header, http.Request.

TestHeaderREMatcher

References: context.WithValue, fmt.Sprintf, http.Header, http.Request, httptest.NewRecorder, url.URL.

TestHostMatcher

References: context.WithValue, http.Request, os.Setenv.

TestMatchExpressionMatch

References: context.Background, context.WithValue, httptest.NewRecorder, httptest.NewRequest, pem.Decode, testing.T, tls.ConnectionState, x509.Certificate, x509.ParseCertificate.

TestMatchExpressionProvision

References: context.Background, testing.T.

TestMetricsInstrumentedHandler

References: context.Background, errors.New, http.Request, http.ResponseWriter, http.StatusTooManyRequests, httptest.NewRecorder, httptest.NewRequest, strings.NewReader, sync.Once, testutil.GatherAndCompare, testutil.ToFloat64.

TestMetricsInstrumentedHandlerPerHost

References: context.Background, errors.New, http.Request, http.ResponseWriter, http.StatusTooManyRequests, httptest.NewRecorder, httptest.NewRequest, strings.NewReader, sync.Once, testutil.GatherAndCompare, testutil.ToFloat64.

TestNotMatcher

References: context.WithValue, http.Request, url.URL.

TestPathMatcher

References: context.WithValue, http.Request, url.ParseRequestURI.

TestPathMatcherWindows

References: context.WithValue, http.Request, runtime.GOOS, url.URL.

TestPathREMatcher

References: context.WithValue, fmt.Sprintf, http.Request, httptest.NewRecorder, url.ParseRequestURI.

TestQueryMatcher

References: context.WithValue, http.Request, url.Parse.

TestResponseMatcher

References: http.Header.

TestResponseRecorderReadFrom

References: bytes.Buffer, http.Header, io.Copy, io.Reader, strings.NewReader, testing.T.

TestResponseWriterWrapperReadFrom

References: io.Copy, io.Reader, strings.NewReader, testing.T.

TestResponseWriterWrapperUnwrap

TestSanitizedPathJoin

References: filepath.FromSlash, filepath.Join, runtime.GOOS, url.Parse.

TestServerNameFromContext

References: context.Background, context.WithValue.

TestServer_DetermineTrustedProxy_MatchLeftMostValidIp

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_MatchRightMostUntrusted

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_MatchRightMostUntrustedFirst

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_MatchRightMostUntrustedSkippingEmpty

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_MatchRightMostUntrustedSkippingTrusted

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_MultipleTrustedClientHeaders

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_MultipleTrustedPrefixes

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_NoConfig

References: assert.Equal, assert.False, httptest.NewRequest.

TestServer_DetermineTrustedProxy_NoConfigIpv6

References: assert.Equal, assert.False, httptest.NewRequest.

TestServer_DetermineTrustedProxy_NoConfigIpv6Zones

References: assert.Equal, assert.False, httptest.NewRequest.

TestServer_DetermineTrustedProxy_TrustedLoopback

References: assert.Equal, assert.True, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_DetermineTrustedProxy_UntrustedPrefix

References: assert.Equal, assert.False, httptest.NewRequest, netip.ParsePrefix, netip.Prefix.

TestServer_LogRequest

References: assert.JSONEq, bytes.Buffer, context.Background, context.WithValue, http.MethodGet, httptest.NewRecorder, httptest.NewRequest, time.Millisecond.

TestServer_LogRequest_WithTrace

References: assert.JSONEq, bytes.Buffer, context.Background, context.WithValue, http.MethodGet, httptest.NewRecorder, httptest.NewRequest, time.Millisecond, zap.String.

TestServer_TrustedRealClientIP_IncludesPort

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_MultipleTrustedHeaderValidArray

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_NoTrustedHeaders

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_OneTrustedHeaderEmpty

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_OneTrustedHeaderInvalid

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_OneTrustedHeaderValid

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_OneTrustedHeaderValidArray

References: assert.Equal, httptest.NewRequest.

TestServer_TrustedRealClientIP_SkipsInvalidIps

References: assert.Equal, httptest.NewRequest.

TestStaticResponseHandler

References: http.Header, http.StatusNotFound, httptest.NewRecorder, io.ReadAll, strconv.Itoa.

TestVarREMatcher

References: context.WithValue, fmt.Sprintf, http.MethodGet, http.Request, httptest.NewRecorder, testing.T, url.URL.

Benchmark functions

BenchmarkHeaderREMatcher

References: context.WithValue, http.Header, http.Request, httptest.NewRecorder, url.URL.

BenchmarkHostMatcherWithPlaceholder

References: context.WithValue, http.Request, os.Setenv.

BenchmarkHostMatcherWithoutPlaceholder

References: context.WithValue, http.Request.

BenchmarkLargeHostMatcher

References: context.WithValue, fmt.Sprintf, http.Request.

BenchmarkMatchExpressionMatch

References: context.WithValue, httptest.NewRecorder, httptest.NewRequest, pem.Decode, testing.B, tls.ConnectionState, x509.Certificate, x509.ParseCertificate.

BenchmarkServer_LogRequest

References: context.Background, context.WithValue, http.MethodGet, httptest.NewRecorder, httptest.NewRequest, io.Discard, time.Millisecond.

BenchmarkServer_LogRequest_NopLogger

References: context.Background, context.WithValue, http.MethodGet, httptest.NewRecorder, httptest.NewRequest, time.Millisecond, zap.NewNop.

BenchmarkServer_LogRequest_WithTrace

References: context.Background, context.WithValue, http.MethodGet, httptest.NewRecorder, httptest.NewRequest, io.Discard, time.Millisecond, zap.String.