Go API Documentation

github.com/caddyserver/caddy/v2

No package summary is available.

Package

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

Constants

Vars

ConfigAutosavePath is the default path to which the last config will be persisted.

CustomVersion is an optional string that overrides Caddy's reported version. It can be helpful when downstream packagers need to manually set Caddy's version. If no other version information is available, the short form version (see Version()) will be set to CustomVersion, and the full version will include CustomVersion at the beginning.

Set this variable during go build with -ldflags:

-ldflags '-X github.com/caddyserver/caddy/v2.CustomVersion=v2.6.2'

for example.

DefaultStorage is Caddy's default storage module.

ErrEventAborted cancels an event.

ErrNotConfigured indicates a module is not configured.

adminMetrics is a collection of metrics that can be tracked for the admin API.

This buffer pool is used to keep buffers for reading the config file during eTag header generation

errFakeClosed is the underlying error value returned by fakeCloseListener.Accept() after Close() has been called, indicating that it is pretending to be closed so that the server using it can terminate, while the underlying socket is actually left open.

errInternalRedir indicates an internal redirect and is useful when admin API handlers rewrite the request; in that case, authentication and authorization needs to happen again for the rewritten request.

errSameConfig is returned if the new config is the same as the old one. This isn't usually an actual, actionable error; it's mostly a sentinel value.

globalMetrics is a collection of metrics that can be tracked for Caddy global state

idRegexp is used to match ID fields and their associated values in the config. It also matches adjacent commas so that syntax can be preserved no matter where in the object the field appears. It supports string and most numeric values.

listenerPool stores and allows reuse of active listeners.

nowFunc is a variable so tests can change it in order to obtain a deterministic time.

pidfile is the name of the pidfile, if any.

socketFiles is a fd -> *os.File map used to make a FileListener/FilePacketConn from a socket file descriptor.

socketFilesMu synchronizes socketFiles insertions

unixSockets keeps track of the currently-active unix sockets so we can transfer their FDs gracefully during reloads.

Types

APIError

APIError is a structured error that every API handler should return for consistency in logging and client responses. If Message is unset, then Err.Error() will be serialized in its place.

Field name Field type Comment
HTTPStatus

int

No comment on field.
Err

error

No comment on field.
Message

string

No comment on field.

AdminAccess

AdminAccess specifies what permissions an identity or group of identities are granted.

Field name Field type Comment
PublicKeys

[]string

Base64-encoded DER certificates containing public keys to accept. (The contents of PEM certificate blocks are base64-encoded DER.) Any of these public keys can appear in any part of a verified chain.

Permissions

[]AdminPermissions

Limits what the associated identities are allowed to do. If unspecified, all permissions are granted.

publicKeys

[]crypto.PublicKey

No comment on field.

AdminConfig

AdminConfig configures Caddy's API endpoint, which is used to manage Caddy while it is running.

Field name Field type Comment
Disabled

bool

If true, the admin endpoint will be completely disabled. Note that this makes any runtime changes to the config impossible, since the interface to do so is through the admin endpoint.

Listen

string

The address to which the admin endpoint's listener should bind itself. Can be any single network address that can be parsed by Caddy. Accepts placeholders. Default: the value of the CADDY_ADMIN environment variable, or localhost:2019 otherwise.

Remember: When changing this value through a config reload, be sure to use the --address CLI flag to specify the current admin address if the currently-running admin endpoint is not the default address.

EnforceOrigin

bool

If true, CORS headers will be emitted, and requests to the API will be rejected if their Host and Origin headers do not match the expected value(s). Use origins to customize which origins/hosts are allowed. If origins is not set, the listen address is the only value allowed by default. Enforced only on local (plaintext) endpoint.

Origins

[]string

The list of allowed origins/hosts for API requests. Only needed if accessing the admin endpoint from a host different from the socket's network interface or if enforce_origin is true. If not set, the listener address will be the default value. If set but empty, no origins will be allowed. Enforced only on local (plaintext) endpoint.

Config

*ConfigSettings

Options pertaining to configuration management.

Identity

*IdentityConfig

Options that establish this server's identity. Identity refers to credentials which can be used to uniquely identify and authenticate this server instance. This is required if remote administration is enabled (but does not require remote administration to be enabled). Default: no identity management.

Remote

*RemoteAdmin

Options pertaining to remote administration. By default, remote administration is disabled. If enabled, identity management must also be configured, as that is how the endpoint is secured. See the neighboring "identity" object.

EXPERIMENTAL: This feature is subject to change.

routers

[]AdminRouter

Holds onto the routers so that we can later provision them if they require provisioning.

AdminHandler

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

If any handler encounters an error, it should be returned for proper handling.

Field name Field type Comment
type

any

No comment on field.

AdminHandlerFunc

AdminHandlerFunc is a convenience type like http.HandlerFunc.

Field name Field type Comment
type

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

No comment on field.

AdminPermissions

AdminPermissions specifies what kinds of requests are allowed to be made to the admin endpoint.

Field name Field type Comment
Paths

[]string

The API paths allowed. Paths are simple prefix matches. Any subpath of the specified paths will be allowed.

Methods

[]string

The HTTP methods allowed for the given paths.

AdminRoute

AdminRoute represents a route for the admin endpoint.

Field name Field type Comment
Pattern

string

No comment on field.
Handler

AdminHandler

No comment on field.

AdminRouter

AdminRouter is a type which can return routes for the admin API.

Field name Field type Comment
type

any

No comment on field.

App

App is a thing that Caddy runs.

Field name Field type Comment
type

any

No comment on field.

BaseLog

BaseLog contains the common logging parameters for logging.

Field name Field type Comment
WriterRaw

json.RawMessage

The module that writes out log entries for the sink.

EncoderRaw

json.RawMessage

The encoder is how the log entries are formatted or encoded.

CoreRaw

json.RawMessage

Tees entries through a zap.Core module which can extract log entry metadata and fields for further processing.

Level

string

Level is the minimum level to emit, and is inclusive. Possible levels: DEBUG, INFO, WARN, ERROR, PANIC, and FATAL

Sampling

*LogSampling

Sampling configures log entry sampling. If enabled, only some log entries will be emitted. This is useful for improving performance on extremely high-pressure servers.

WithCaller

bool

If true, the log entry will include the caller's file name and line number. Default off.

WithCallerSkip

int

If non-zero, and with_caller is true, this many stack frames will be skipped when determining the caller. Default 0.

WithStacktrace

string

If not empty, the log entry will include a stack trace for all logs at the given level or higher. See level for possible values. Default off.

writerOpener

WriterOpener

No comment on field.
writer

io.WriteCloser

No comment on field.
encoder

zapcore.Encoder

No comment on field.
levelEnabler

zapcore.LevelEnabler

No comment on field.
core

zapcore.Core

No comment on field.

CleanerUpper

CleanerUpper is implemented by modules which may have side-effects such as opened files, spawned goroutines, or allocated some sort of non-stack state when they were provisioned. This method should deallocate/cleanup those resources to prevent memory leaks. Cleanup should be fast and efficient. Cleanup should work even if Provision returns an error, to allow cleaning up from partial provisionings.

Field name Field type Comment
type

any

No comment on field.

CloudEvent

CloudEvent is a JSON-serializable structure that is compatible with the CloudEvents specification. See https://cloudevents.io. EXPERIMENTAL: Subject to change.

Field name Field type Comment
ID

string

No comment on field.
Source

string

No comment on field.
SpecVersion

string

No comment on field.
Type

string

No comment on field.
Time

time.Time

No comment on field.
DataContentType

string

No comment on field.
Data

json.RawMessage

No comment on field.

Config

Config is the top (or beginning) of the Caddy configuration structure. Caddy config is expressed natively as a JSON document. If you prefer not to work with JSON directly, there are many config adapters available that can convert various inputs into Caddy JSON.

Many parts of this config are extensible through the use of Caddy modules. Fields which have a json.RawMessage type and which appear as dots (•••) in the online docs can be fulfilled by modules in a certain module namespace. The docs show which modules can be used in a given place.

Whenever a module is used, its name must be given either inline as part of the module, or as the key to the module's value. The docs will make it clear which to use.

Generally, all config settings are optional, as it is Caddy convention to have good, documented default values. If a parameter is required, the docs should say so.

Go programs which are directly building a Config struct value should take care to populate the JSON-encodable fields of the struct (i.e. the fields with json struct tags) if employing the module lifecycle (e.g. Provision method calls).

Field name Field type Comment
Admin

*AdminConfig

No comment on field.
Logging

*Logging

No comment on field.
StorageRaw

json.RawMessage

StorageRaw is a storage module that defines how/where Caddy stores assets (such as TLS certificates). The default storage module is caddy.storage.file_system (the local file system), and the default path depends on the OS and environment.

AppsRaw

ModuleMap

AppsRaw are the apps that Caddy will load and run. The app module name is the key, and the app's config is the associated value.

apps

map[string]App

No comment on field.
storage

certmagic.Storage

No comment on field.
eventEmitter

eventEmitter

No comment on field.
cancelFunc

context.CancelFunc

No comment on field.
fileSystems

FileSystems

fileSystems is a dict of fileSystems that will later be loaded from and added to.

ConfigLoader

ConfigLoader is a type that can load a Caddy config. If the return value is non-nil, it must be valid Caddy JSON; if nil or with non-nil error, it is considered to be a no-op load and may be retried later.

Field name Field type Comment
type

any

No comment on field.

ConfigSettings

ConfigSettings configures the management of configuration.

Field name Field type Comment
Persist

*bool

Whether to keep a copy of the active config on disk. Default is true. Note that "pulled" dynamic configs (using the neighboring "load" module) are not persisted; only configs that are pushed to Caddy get persisted.

LoadRaw

json.RawMessage

Loads a new configuration. This is helpful if your configs are managed elsewhere and you want Caddy to pull its config dynamically when it starts. The pulled config completely replaces the current one, just like any other config load. It is an error if a pulled config is configured to pull another config without a load_delay, as this creates a tight loop.

EXPERIMENTAL: Subject to change.

LoadDelay

Duration

The duration after which to load config. If set, config will be pulled from the config loader after this duration. A delay is required if a dynamically-loaded config is configured to load yet another config. To load configs on a regular interval, ensure this value is set the same on all loaded configs; it can also be variable if needed, and to stop the loop, simply remove dynamic config loading from the next-loaded config.

EXPERIMENTAL: Subject to change.

ConfiguresFormatterDefault

ConfiguresFormatterDefault is an optional interface that encoder modules can implement to configure the default format of their encoder. This is useful for encoders which nest an encoder, that needs to know the writer in order to determine the correct default.

Field name Field type Comment
type

any

No comment on field.

Constructor

Constructor is a function that returns a new value that can destruct itself when it is no longer needed.

Field name Field type Comment
type

func() (Destructor, error)

No comment on field.

Context

Context is a type which defines the lifetime of modules that are loaded and provides access to the parent configuration that spawned the modules which are loaded. It should be used with care and wrapped with derivation functions from the standard context package only if you don't need the Caddy specific features. These contexts are canceled when the lifetime of the modules loaded from it is over.

Use NewContext() to get a valid value (but most modules will not actually need to do this).

Field name Field type Comment

context.Context

No comment on field.
moduleInstances

map[string][]Module

No comment on field.
cfg

*Config

No comment on field.
ancestry

[]Module

No comment on field.
cleanupFuncs

[]func()

No comment on field.
exitFuncs

[]func(context.Context)

No comment on field.
metricsRegistry

*prometheus.Registry

No comment on field.

CtxKey

CtxKey is a value type for use with context.WithValue.

Field name Field type Comment
type

string

No comment on field.

CustomLog

CustomLog represents a custom logger configuration.

By default, a log will emit all log entries. Some entries will be skipped if sampling is enabled. Further, the Include and Exclude parameters define which loggers (by name) are allowed or rejected from emitting in this log. If both Include and Exclude are populated, their values must be mutually exclusive, and longer namespaces have priority. If neither are populated, all logs are emitted.

Field name Field type Comment

BaseLog

No comment on field.
Include

[]string

Include defines the names of loggers to emit in this log. For example, to include only logs emitted by the admin API, you would include "admin.api".

Exclude

[]string

Exclude defines the names of loggers that should be skipped by this log. For example, to exclude only HTTP access logs, you would exclude "http.log.access".

Destructor

Destructor is a value that can clean itself up when it is deallocated.

Field name Field type Comment
type

any

No comment on field.

Duration

Duration can be an integer or a string. An integer is interpreted as nanoseconds. If a string, it is a Go time.Duration value such as 300ms, 1.5h, or 2h45m; valid units are ns, us/µs, ms, s, m, h, and d.

Field name Field type Comment
type

time.Duration

No comment on field.

Event

Event represents something that has happened or is happening. An Event value is not synchronized, so it should be copied if being used in goroutines.

EXPERIMENTAL: Events are subject to change.

Field name Field type Comment
Aborted

error

If non-nil, the event has been aborted, meaning propagation has stopped to other handlers and the code should stop what it was doing. Emitters may choose to use this as a signal to adjust their code path appropriately.

Data

map[string]any

The data associated with the event. Usually the original emitter will be the only one to set or change these values, but the field is exported so handlers can have full access if needed. However, this map is not synchronized, so handlers must not use this map directly in new goroutines; instead, copy the map to use it in a goroutine. Data may be nil.

id

uuid.UUID

No comment on field.
ts

time.Time

No comment on field.
name

string

No comment on field.
origin

Module

No comment on field.

FileSystems

This type doesn't have documentation.

Field name Field type Comment
type

any

No comment on field.

IdentityConfig

IdentityConfig configures management of this server's identity. An identity consists of credentials that uniquely verify this instance; for example, TLS certificates (public + private key pairs).

Field name Field type Comment
Identifiers

[]string

List of names or IP addresses which refer to this server. Certificates will be obtained for these identifiers so secure TLS connections can be made using them.

IssuersRaw

[]json.RawMessage

Issuers that can provide this admin endpoint its identity certificate(s). Default: ACME issuers configured for ZeroSSL and Let's Encrypt. Be sure to change this if you require credentials for private identifiers.

issuers

[]certmagic.Issuer

No comment on field.

ListenerFunc

ListenerFunc is a function that can return a listener given a network and address. The listeners must be capable of overlapping: with Caddy, new configs are loaded before old ones are unloaded, so listeners may overlap briefly if the configs both need the same listener. EXPERIMENTAL and subject to change.

Field name Field type Comment
type

func(ctx context.Context, network, host, portRange string, portOffset uint, cfg net.ListenConfig) (any, error)

No comment on field.

ListenerWrapper

ListenerWrapper is a type that wraps a listener so it can modify the input listener's methods. Modules that implement this interface are found in the caddy.listeners namespace. Usually, to wrap a listener, you will define your own struct type that embeds the input listener, then implement your own methods that you want to wrap, calling the underlying listener's methods where appropriate.

Field name Field type Comment
type

any

No comment on field.

LogSampling

LogSampling configures log entry sampling.

Field name Field type Comment
Interval

time.Duration

The window over which to conduct sampling.

First

int

Log this many entries within a given level and message for each interval.

Thereafter

int

If more entries with the same level and message are seen during the same interval, keep one in this many entries until the end of the interval.

Logging

Logging facilitates logging within Caddy. The default log is called "default" and you can customize it. You can also define additional logs.

By default, all logs at INFO level and higher are written to standard error ("stderr" writer) in a human-readable format ("console" encoder if stdout is an interactive terminal, "json" encoder otherwise).

All defined logs accept all log entries by default, but you can filter by level and module/logger names. A logger's name is the same as the module's name, but a module may append to logger names for more specificity. For example, you can filter logs emitted only by HTTP handlers using the name "http.handlers", because all HTTP handler module names have that prefix.

Caddy logs (except the sink) are zero-allocation, so they are very high-performing in terms of memory and CPU time. Enabling sampling can further increase throughput on extremely high-load servers.

Field name Field type Comment
Sink

*SinkLog

Sink is the destination for all unstructured logs emitted from Go's standard library logger. These logs are common in dependencies that are not designed specifically for use in Caddy. Because it is global and unstructured, the sink lacks most advanced features and customizations.

Logs

map[string]*CustomLog

Logs are your logs, keyed by an arbitrary name of your choosing. The default log can be customized by defining a log called "default". You can further define other logs and filter what kinds of entries they accept.

writerKeys

[]string

a list of all keys for open writers; all writers that are opened to provision this logging config must have their keys added to this list so they can be closed when cleaning up

Module

Module is a type that is used as a Caddy module. In addition to this interface, most modules will implement some interface expected by their host module in order to be useful. To learn which interface(s) to implement, see the documentation for the host module. At a bare minimum, this interface, when implemented, only provides the module's ID and constructor function.

Modules will often implement additional interfaces including Provisioner, Validator, and CleanerUpper. If a module implements these interfaces, their methods are called during the module's lifespan.

When a module is loaded by a host module, the following happens: 1) ModuleInfo.New() is called to get a new instance of the module. 2) The module's configuration is unmarshaled into that instance. 3) If the module is a Provisioner, the Provision() method is called. 4) If the module is a Validator, the Validate() method is called. 5) The module will probably be type-asserted from 'any' to some other, more useful interface expected by the host module. For example, HTTP handler modules are type-asserted as caddyhttp.MiddlewareHandler values. 6) When a module's containing Context is canceled, if it is a CleanerUpper, its Cleanup() method is called.

Field name Field type Comment
type

any

No comment on field.

ModuleID

ModuleID is a string that uniquely identifies a Caddy module. A module ID is lightly structured. It consists of dot-separated labels which form a simple hierarchy from left to right. The last label is the module name, and the labels before that constitute the namespace (or scope).

Thus, a module ID has the form: <namespace>.<name>

An ID with no dot has the empty namespace, which is appropriate for app modules (these are "top-level" modules that Caddy core loads and runs).

Module IDs should be lowercase and use underscores (_) instead of spaces.

Examples of valid IDs:

  • http
  • http.handlers.file_server
  • caddy.logging.encoders.json

Field name Field type Comment
type

string

No comment on field.

ModuleInfo

ModuleInfo represents a registered Caddy module.

Field name Field type Comment
ID

ModuleID

ID is the "full name" of the module. It must be unique and properly namespaced.

New

func() Module

New returns a pointer to a new, empty instance of the module's type. This method must not have any side-effects, and no other initialization should occur within it. Any initialization of the returned value should be done in a Provision() method (see the Provisioner interface).

ModuleMap

ModuleMap is a map that can contain multiple modules, where the map key is the module's name. (The namespace is usually read from an associated field's struct tag.) Because the module's name is given as the key in a module map, the name does not have to be given in the json.RawMessage.

Field name Field type Comment
type

map[string]json.RawMessage

No comment on field.

NetworkAddress

NetworkAddress represents one or more network addresses. It contains the individual components for a parsed network address of the form accepted by ParseNetworkAddress().

Field name Field type Comment
Network

string

Should be a network value accepted by Go's net package or by a plugin providing a listener for that network type.

Host

string

The "main" part of the network address is the host, which often takes the form of a hostname, DNS name, IP address, or socket path.

StartPort

uint

For addresses that contain a port, ranges are given by [StartPort, EndPort]; i.e. for a single port, StartPort and EndPort are the same. For no port, they are 0.

EndPort

uint

No comment on field.

Provisioner

Provisioner is implemented by modules which may need to perform some additional "setup" steps immediately after being loaded. Provisioning should be fast (imperceptible running time). If any side-effects result in the execution of this function (e.g. creating global state, any other allocations which require garbage collection, opening files, starting goroutines etc.), be sure to clean up properly by implementing the CleanerUpper interface to avoid leaking resources.

Field name Field type Comment
type

any

No comment on field.

ProxyFuncProducer

ProxyFuncProducer is implemented by modules which produce a function that returns a URL to use as network proxy. Modules in the namespace caddy.network_proxy must implement this interface.

Field name Field type Comment
type

any

No comment on field.

RemoteAdmin

RemoteAdmin enables and configures remote administration. If enabled, a secure listener enforcing mutual TLS authentication will be started on a different port from the standard plaintext admin server.

This endpoint is secured using identity management, which must be configured separately (because identity management does not depend on remote administration). See the admin/identity config struct.

EXPERIMENTAL: Subject to change.

Field name Field type Comment
Listen

string

The address on which to start the secure listener. Accepts placeholders. Default: :2021

AccessControl

[]*AdminAccess

List of access controls for this secure admin endpoint. This configures TLS mutual authentication (i.e. authorized client certificates), but also application-layer permissions like which paths and methods each identity is authorized for.

ReplacementFunc

ReplacementFunc is a function that is called when a replacement is being performed. It receives the variable (i.e. placeholder name) and the value that will be the replacement, and returns the value that will actually be the replacement, or an error. Note that errors are sometimes ignored by replacers.

Field name Field type Comment
type

func(variable string, val any) (any, error)

No comment on field.

Replacer

Replacer can replace values in strings. A default/empty Replacer is not valid; use NewReplacer to make one.

Field name Field type Comment
providers

[]replacementProvider

No comment on field.
static

map[string]any

No comment on field.
mapMutex

*sync.RWMutex

No comment on field.

ReplacerFunc

ReplacerFunc is a function that returns a replacement for the given key along with true if the function is able to service that key (even if the value is blank). If the function does not recognize the key, false should be returned.

Field name Field type Comment
type

func(key string) (any, bool)

No comment on field.

SinkLog

SinkLog configures the default Go standard library global logger in the log package. This is necessary because module dependencies which are not built specifically for Caddy will use the standard logger. This is also known as the "sink" logger.

Field name Field type Comment

BaseLog

No comment on field.

StorageConverter

StorageConverter is a type that can convert itself to a valid, usable certmagic.Storage value. (The value might be short-lived.) This interface allows us to adapt any CertMagic storage implementation into a consistent API for Caddy configuration.

Field name Field type Comment
type

any

No comment on field.

UsagePool

UsagePool is a thread-safe map that pools values based on usage (reference counting). Values are only inserted if they do not already exist. There are two ways to add values to the pool:

  1. LoadOrStore will increment usage and store the value immediately if it does not already exist.
  2. LoadOrNew will atomically check for existence and construct the value immediately if it does not already exist, or increment the usage otherwise, then store that value in the pool. When the constructed value is finally deleted from the pool (when its usage reaches 0), it will be cleaned up by calling Destruct().

The use of LoadOrNew allows values to be created and reused and finally cleaned up only once, even though they may have many references throughout their lifespan. This is helpful, for example, when sharing thread-safe io.Writers that you only want to open and close once.

There is no way to overwrite existing keys in the pool without first deleting it as many times as it was stored. Deleting too many times will panic.

The implementation does not use a sync.Pool because UsagePool needs additional atomicity to run the constructor functions when creating a new value when LoadOrNew is used. (We could probably use sync.Pool but we'd still have to layer our own additional locks on top.)

An empty UsagePool is NOT safe to use; always call NewUsagePool() to make a new one.

Field name Field type Comment

sync.RWMutex

No comment on field.
pool

map[any]*usagePoolVal

No comment on field.

Validator

Validator is implemented by modules which can verify that their configurations are valid. This method will be called after Provision() (if implemented). Validation should always be fast (imperceptible running time) and an error must be returned if the module's configuration is invalid.

Field name Field type Comment
type

any

No comment on field.

WriterOpener

WriterOpener is a module that can open a log writer. It can return a human-readable string representation of itself so that operators can understand where the logs are going.

Field name Field type Comment
type

any

No comment on field.

StdoutWriter, StderrWriter, DiscardWriter

This type doesn't have documentation.

adminHandler

This type doesn't have documentation.

Field name Field type Comment
mux

*http.ServeMux

No comment on field.
enforceOrigin

bool

security for local/plaintext endpoint

enforceHost

bool

No comment on field.
allowedOrigins

[]*url.URL

No comment on field.
remoteControl

*RemoteAdmin

security for remote/encrypted endpoint

contextAndCancelFunc

contextAndCancelFunc groups context and its cancelFunc

Field name Field type Comment

context.Context

No comment on field.

context.CancelFunc

No comment on field.

defaultCustomLog

This type doesn't have documentation.

Field name Field type Comment

*CustomLog

No comment on field.
logger

*zap.Logger

No comment on field.

delegator

This type doesn't have documentation.

Field name Field type Comment

http.ResponseWriter

No comment on field.
status

int

No comment on field.

deleteListener

deleteListener is a type that simply deletes itself from the listenerPool when it closes. It is used solely for the purpose of reference counting (i.e. counting how many configs are using a given socket).

Field name Field type Comment

net.Listener

No comment on field.
lnKey

string

No comment on field.

deletePacketConn

deletePacketConn is like deleteListener, but for net.PacketConns.

Field name Field type Comment

net.PacketConn

No comment on field.
lnKey

string

No comment on field.

eventEmitter

eventEmitter is a small interface that inverts dependencies for the caddyevents package, so the core can emit events without an import cycle (i.e. the caddy package doesn't have to import the caddyevents package, which imports the caddy package).

Field name Field type Comment
type

any

No comment on field.

fakeCloseQuicListener

This type doesn't have documentation.

Field name Field type Comment
closed

int32

No comment on field.

*sharedQuicListener

No comment on field.
context

context.Context

No comment on field.
contextCancel

context.CancelFunc

No comment on field.

fileReplacementProvider

fileReplacementsProvider handles {file.*} replacements, reading a file from disk and replacing with its contents.

filteringCore

filteringCore filters log entries based on logger name, according to the rules of a CustomLog.

Field name Field type Comment

zapcore.Core

No comment on field.
cl

*CustomLog

No comment on field.

globalDefaultReplacementProvider

globalDefaultReplacementsProvider handles replacements that can be used in any context, such as system variables, time, or environment variables.

loggableURLArray

This type doesn't have documentation.

Field name Field type Comment
type

[]*url.URL

No comment on field.

notClosable

notClosable is an io.WriteCloser that can't be closed.

Field name Field type Comment

io.Writer

No comment on field.

replacementProvider

replacementProvider is a type that can provide replacements for placeholders. Allows for type assertion to determine which type of provider it is.

Field name Field type Comment
type

any

No comment on field.

sharedQUICState

sharedQUICState manages GetConfigForClient see issue: https://github.com/caddyserver/caddy/pull/4849

Field name Field type Comment
rmu

sync.RWMutex

No comment on field.
tlsConfs

map[*tls.Config]contextAndCancelFunc

No comment on field.
activeTlsConf

*tls.Config

No comment on field.

sharedQuicListener

sharedQuicListener is like sharedListener, but for quic.EarlyListeners.

Field name Field type Comment

*quic.EarlyListener

No comment on field.
packetConn

net.PacketConn

No comment on field.
sqs

*sharedQUICState

No comment on field.
key

string

No comment on field.

unixConn

This type doesn't have documentation.

Field name Field type Comment

*net.UnixConn

No comment on field.
mapKey

string

No comment on field.
count

*int32

No comment on field.

unixListener

This type doesn't have documentation.

Field name Field type Comment

*net.UnixListener

No comment on field.
mapKey

string

No comment on field.
count

*int32

No comment on field.

usagePoolVal

This type doesn't have documentation.

Field name Field type Comment
refs

int32

No comment on field.
value

any

No comment on field.
err

error

No comment on field.

sync.RWMutex

No comment on field.

writerDestructor

This type doesn't have documentation.

Field name Field type Comment

io.WriteCloser

No comment on field.

Functions

func ActiveContext

ActiveContext returns the currently-active context. This function is experimental and might be changed or removed in the future.

func AppConfigDir

AppConfigDir returns the directory where to store user's config.

If XDG_CONFIG_HOME is set, it returns: $XDG_CONFIG_HOME/caddy. Otherwise, os.UserConfigDir() is used; if successful, it appends "Caddy" (Windows & Mac) or "caddy" (every other OS) to the path. If it returns an error, the fallback path "./caddy" is returned.

The config directory is not guaranteed to be different from AppDataDir().

Unlike os.UserConfigDir(), this function prefers the XDG_CONFIG_HOME env var on all platforms, not just Unix.

Ref: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html

Uses: filepath.Join, os.Getenv, os.UserConfigDir, runtime.GOOS, zap.Error.

func AppDataDir

AppDataDir returns a directory path that is suitable for storing application data on disk. It uses the environment for finding the best place to store data, and appends a "caddy" or "Caddy" (depending on OS and environment) subdirectory.

For a base directory path: If XDG_DATA_HOME is set, it returns: $XDG_DATA_HOME/caddy; otherwise, on Windows it returns: %AppData%/Caddy, on Mac: $HOME/Library/Application Support/Caddy, on Plan9: $home/lib/caddy, on Android: $HOME/caddy, and on everything else: $HOME/.local/share/caddy.

If a data directory cannot be determined, it returns "./caddy" (this is not ideal, and the environment should be fixed).

The data directory is not guaranteed to be different from AppConfigDir().

Ref: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html

Uses: filepath.Join, os.Getenv, runtime.GOOS.

func Exiting

Exiting returns true if the process is exiting. EXPERIMENTAL API: subject to change or removal.

Uses: atomic.LoadInt32.

func FastAbs

FastAbs is an optimized version of filepath.Abs for Unix systems, since we don't expect the working directory to ever change once Caddy is running. Avoid the os.Getwd() syscall overhead. It's overall the same as stdlib's implementation, the difference being cached working directory.

Uses: filepath.Clean, filepath.IsAbs, filepath.Join.

func GetModule

GetModule returns module information from its ID (full name).

Uses: fmt.Errorf.

func GetModuleID

GetModuleID returns a module's ID from an instance of its value. If the value is not a module, an empty string will be returned.

func GetModuleName

GetModuleName returns a module's name (the last label of its ID) from an instance of its value. If the value is not a module, an empty string will be returned.

func GetModules

GetModules returns all modules in the given scope/namespace. For example, a scope of "foo" returns modules named "foo.bar", "foo.loo", but not "bar", "foo.bar.loo", etc. An empty scope returns top-level modules, for example "foo" or "bar". Partial scopes are not matched (i.e. scope "foo.ba" does not match name "foo.bar").

Because modules are registered to a map under the hood, the returned slice will be sorted to keep it deterministic.

Uses: sort.Slice, strings.Split.

func HomeDir

HomeDir returns the best guess of the current user's home directory from environment variables. If unknown, "." (the current directory) is returned instead, except GOOS=android, which returns "/sdcard".

Uses: runtime.GOOS.

func InstanceID

InstanceID returns the UUID for this instance, and generates one if it does not already exist. The UUID is stored in the local data directory, regardless of storage configuration, since each instance is intended to have its own unique ID.

Uses: errors.Is, filepath.Join, fs.ErrNotExist, os.MkdirAll, os.ReadFile, os.WriteFile, uuid.NewRandom, uuid.ParseBytes.

func IsFdNetwork

IsFdNetwork returns true if the netw is a fd network.

Uses: strings.HasPrefix.

func IsUnixNetwork

IsUnixNetwork returns true if the netw is a unix network.

Uses: strings.HasPrefix.

func IsWriterStandardStream

IsWriterStandardStream returns true if the input is a writer-opener to a standard stream (stdout, stderr).

func JoinNetworkAddress

JoinNetworkAddress combines network, host, and port into a single address string of the form accepted by ParseNetworkAddress(). For unix sockets, the network should be "unix" (or "unixgram" or "unixpacket") and the path to the socket should be given as the host parameter.

Uses: net.JoinHostPort.

func ListenerUsage

ListenerUsage returns the current usage count of the given listener address.

func Load

Load loads the given config JSON and runs it only if it is different from the current config or forceReload is true.

Uses: errors.Is, http.MethodPost, notify.Error, notify.Ready, notify.Reloading, zap.Error, zap.String.

func Log

Log returns the current default logger.

func Modules

Modules returns the names of all registered modules in ascending lexicographical order.

Uses: sort.Strings.

func NewContext

NewContext provides a new context derived from the given context ctx. Normally, you will not need to call this function unless you are loading modules which have a different lifespan than the ones for the context the module was provisioned with. Be sure to call the cancel func when the context is to be cleaned up so that modules which are loaded will be properly unloaded. See standard library context package's documentation.

Uses: context.WithCancel, log.Printf, prometheus.NewPedanticRegistry.

func NewEmptyReplacer

NewEmptyReplacer returns a new Replacer, without the global default replacements.

Uses: sync.RWMutex.

func NewEvent

NewEvent creates a new event, but does not emit the event. To emit an event, call Emit() on the current instance of the caddyevents app insteaad.

EXPERIMENTAL: Subject to change.

Uses: fmt.Errorf, strings.ToLower, time.Now, uuid.NewRandom.

func NewReplacer

NewReplacer returns a new Replacer.

Uses: sync.RWMutex.

func NewUsagePool

NewUsagePool returns a new usage pool that is ready to use.

func OnExit

OnExit registers a callback to invoke during process exit. This registration is PROCESS-GLOBAL, meaning that each function should only be registered once forever, NOT once per config load (etc).

EXPERIMENTAL API: subject to change or removal.

func PIDFile

PIDFile writes a pidfile to the file at filename. It will get deleted before the process gracefully exits.

Uses: os.Getpid, os.WriteFile, strconv.Itoa.

func ParseDuration

ParseDuration parses a duration string, adding support for the "d" unit meaning number of days, where a day is assumed to be 24h. The maximum input string length is 1024.

Uses: fmt.Errorf, strconv.FormatFloat, strconv.ParseFloat, time.ParseDuration.

func ParseNetworkAddress

ParseNetworkAddress parses addr into its individual components. The input string is expected to be of the form "network/host:port-range" where any part is optional. The default network, if unspecified, is tcp. Port ranges are inclusive.

Network addresses are distinct from URLs and do not use URL syntax.

func ParseNetworkAddressWithDefaults

ParseNetworkAddressWithDefaults is like ParseNetworkAddress but allows the default network and port to be specified.

Uses: fmt.Errorf, strconv.ParseUint, strings.Cut.

func ParseStructTag

ParseStructTag parses a caddy struct tag into its keys and values. It is very simple. The expected syntax is: caddy:"key1=val1 key2=val2 ..."

Uses: fmt.Errorf, strings.Cut, strings.Split.

func ProvisionContext

ProvisionContext creates a new context from the configuration and provisions storage and app modules. The function is intended for testing and advanced use cases only, typically Run should be use to ensure a fully functional caddy instance. EXPERIMENTAL: While this is public the interface and implementation details of this function may change.

func RegisterModule

RegisterModule registers a module by receiving a plain/empty value of the module. For registration to be properly recorded, this should be called in the init phase of runtime. Typically, the module package will do this as a side-effect of being imported. This function panics if the module's info is incomplete or invalid, or if the module is already registered.

Uses: fmt.Sprintf.

func RegisterNetwork

RegisterNetwork registers a network type with Caddy so that if a listener is created for that network type, getListener will be invoked to get the listener. This should be called during init() and will panic if the network type is standard or reserved, or if it is already registered. EXPERIMENTAL and subject to change.

Uses: strings.HasPrefix, strings.ToLower, strings.TrimSpace.

func RemoveMetaFields

RemoveMetaFields removes meta fields like "@id" from a JSON message by using a simple regular expression. (An alternate way to do this would be to delete them from the raw, map[string]any representation as they are indexed, then iterate the index we made and add them back after encoding as JSON, but this is simpler.)

Uses: bytes.HasPrefix, bytes.HasSuffix.

func Run

Run runs the given config, replacing any existing config.

Uses: json.Marshal.

func SplitNetworkAddress

SplitNetworkAddress splits a into its network, host, and port components. Note that port may be a port range (:X-Y), or omitted for unix sockets.

Uses: errors.Join, net.JoinHostPort, net.SplitHostPort, strings.Cut, strings.ToLower, strings.Trim, strings.TrimSpace.

func Stop

Stop stops running the current configuration. It is the antithesis of Run(). This function will log any errors that occur during the stopping of individual apps and continue to stop the others. Stop should only be called if not replacing with a new config.

func StrictUnmarshalJSON

StrictUnmarshalJSON is like json.Unmarshal but returns an error if any of the fields are unrecognized. Useful when decoding module configurations, where you want to be more sure they're correct.

Uses: bytes.NewReader, json.NewDecoder.

func ToString

ToString returns val as a string, as efficiently as possible. EXPERIMENTAL: may be changed or removed later.

Uses: fmt.Sprintf, fmt.Stringer, strconv.FormatFloat, strconv.FormatUint, strconv.Itoa.

func TrapSignals

TrapSignals create signal/interrupt handlers as best it can for the current OS. This is a rather invasive function to call in a Go program that captures signals already, so in that case it would be better to implement these handlers yourself.

func Validate

Validate loads, provisions, and validates cfg, but does not start running it.

func Version

Version returns the Caddy version in a simple/short form, and a full version string. The short form will not have spaces and is intended for User-Agent strings and similar, but may be omitting valuable information. Note that Caddy must be compiled in a special way to properly embed complete version information. First this function tries to get the version from the embedded build info provided by go.mod dependencies; then it tries to get info from embedded VCS information, which requires having built Caddy from a git repository. If no version is available, this function returns "(devel)" because Go uses that, but for the simple form we change it to "unknown". If still no version is available (e.g. no VCS repo), then it will use CustomVersion; CustomVersion is always prepended to the full version string.

See relevant Go issues: https://github.com/golang/go/issues/29228 and https://github.com/golang/go/issues/50603.

This function is experimental and subject to change or removal.

Uses: debug.Module, debug.ReadBuildInfo, fmt.Sprintf, hex.DecodeString, strconv.ParseBool, time.Parse, time.RFC3339, time.RFC822, time.Time.

func (*Context) FileSystems

FileSystems returns a ref to the FilesystemMap. EXPERIMENTAL: This API is subject to change.

Uses: filesystems.FileSystemMap.

func (*Context) GetMetricsRegistry

Returns the active metrics registry for the context EXPERIMENTAL: This API is subject to change.

func (*Context) OnCancel

OnCancel executes f when ctx is canceled.

func (*Context) OnExit

OnExit executes f when the process exits gracefully. The function is only executed if the process is gracefully shut down while this context is active.

EXPERIMENTAL API: subject to change or removal.

func (*Context) WithValue

WithValue returns a new context with the given key-value pair.

Uses: context.WithValue.

func (*Duration) UnmarshalJSON

UnmarshalJSON satisfies json.Unmarshaler.

Uses: io.EOF, json.Unmarshal, strings.Trim, time.Duration.

func (*Logging) Logger

Logger returns a logger that is ready for the module to use.

Uses: zap.Error, zap.New, zap.Option, zap.String, zapcore.Core, zapcore.NewTee.

func (*Replacer) Delete

Delete removes a variable with a static value that was created using Set.

func (*Replacer) Get

Get gets a value from the replacer. It returns the value and whether the variable was known.

func (*Replacer) GetString

GetString is the same as Get, but coerces the value to a string representation as efficiently as possible.

func (*Replacer) Map

Map adds mapFunc to the list of value providers. mapFunc will be executed only at replace-time.

func (*Replacer) ReplaceAll

ReplaceAll efficiently replaces placeholders in input with their values. All placeholders are replaced in the output whether they are recognized or not. Values that are empty string will be substituted with empty.

func (*Replacer) ReplaceFunc

ReplaceFunc is the same as ReplaceAll, but calls f for every replacement to be made, in case f wants to change or inspect the replacement.

func (*Replacer) ReplaceKnown

ReplaceKnown is like ReplaceAll but only replaces placeholders that are known (recognized). Unrecognized placeholders will remain in the output.

func (*Replacer) ReplaceOrErr

ReplaceOrErr is like ReplaceAll, but any placeholders that are empty or not recognized will cause an error to be returned.

func (*Replacer) Set

Set sets a custom variable to a static value.

func (*Replacer) WithoutFile

WithoutFile returns a copy of the current Replacer without support for the {file.*} placeholder, which may be unsafe in some contexts.

EXPERIMENTAL: Subject to change or removal.

func (*UsagePool) Delete

Delete decrements the usage count for key and removes the value from the underlying map if the usage is 0. It returns true if the usage count reached 0 and the value was deleted. It panics if the usage count drops below 0; always call Delete precisely as many times as LoadOrStore.

Uses: atomic.AddInt32, fmt.Sprintf.

func (*UsagePool) LoadOrNew

LoadOrNew loads the value associated with key from the pool if it already exists. If the key doesn't exist, it will call construct to create a new value and then stores that in the pool. An error is only returned if the constructor returns an error. The loaded or constructed value is returned. The loaded return value is true if the value already existed and was loaded, or false if it was newly constructed.

Uses: atomic.AddInt32.

func (*UsagePool) LoadOrStore

LoadOrStore loads the value associated with key from the pool if it already exists, or stores it if it does not exist. It returns the value that was either loaded or stored, and true if the value already existed and was loaded, false if the value didn't exist and was stored.

Uses: atomic.AddInt32.

func (*UsagePool) Range

Range iterates the pool similarly to how sync.Map.Range() does: it calls f for every key in the pool, and if f returns false, iteration is stopped. Ranging does not affect usage counts.

This method is somewhat naive and acquires a read lock on the entire pool during iteration, so do your best to make f() really fast, m'kay?

func (*UsagePool) References

References returns the number of references (count of usages) to a key in the pool, and true if the key exists, or false otherwise.

Uses: atomic.LoadInt32.

func (*delegator) Unwrap

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

func (*delegator) WriteHeader

func (*fakeCloseQuicListener) Accept

Currently Accept ignores the passed context, however a situation where someone would need a hotswappable QUIC-only (not http3, since it uses context.Background here) server on which Accept would be called with non-empty contexts (mind that the default net listeners' Accept doesn't take a context argument) sounds way too rare for us to sacrifice efficiency here.

Uses: atomic.LoadInt32, context.Canceled, errors.Is.

func (*fakeCloseQuicListener) Close

Uses: atomic.CompareAndSwapInt32.

func (*filteringCore) Check

Check only allows the log entry if its logger name is allowed from the include/exclude rules of fc.cl.

func (*filteringCore) With

With properly wraps With.

func (*sharedQuicListener) Destruct

Destruct closes the underlying QUIC listener and its associated net.PacketConn.

func (*unixConn) Close

Uses: atomic.AddInt32, syscall.Unlink.

func (*unixConn) Unwrap

func (*unixListener) Close

Uses: atomic.AddInt32, syscall.Unlink.

func (APIError) Error

func (AdminHandlerFunc) ServeHTTP

ServeHTTP implements the Handler interface.

func (Context) App

App returns the configured app named name. If that app has not yet been loaded and provisioned, it will be immediately loaded and provisioned. If no app with that name is configured, a new empty one will be instantiated instead. (The app module must still be registered.) This must not be called during the Provision/Validate phase to reference a module's own host app (since the parent app module is still in the process of being provisioned, it is not yet ready).

We return any type instead of the App type because it is NOT intended for the caller of this method to be the one to start or stop App modules. The caller is expected to assert to the concrete type.

Uses: fmt.Errorf.

func (Context) AppIfConfigured

AppIfConfigured is like App, but it returns an error if the app has not been configured. This is useful when the app is required and its absence is a configuration error; or when the app is optional and you don't want to instantiate a new one that hasn't been explicitly configured. If the app is not in the configuration, the error wraps ErrNotConfigured.

Uses: fmt.Errorf.

func (Context) IdentityCredentials

IdentityCredentials returns this instance's configured, managed identity credentials that can be used in TLS client authentication.

Uses: fmt.Errorf.

func (Context) LoadModule

LoadModule loads the Caddy module(s) from the specified field of the parent struct pointer and returns the loaded module(s). The struct pointer and its field name as a string are necessary so that reflection can be used to read the struct tag on the field to get the module namespace and inline module name key (if specified).

The field can be any one of the supported raw module types: json.RawMessage, []json.RawMessage, map[string]json.RawMessage, or []map[string]json.RawMessage. ModuleMap may be used in place of map[string]json.RawMessage. The return value's underlying type mirrors the input field's type:

json.RawMessage              => any
[]json.RawMessage            => []any
[][]json.RawMessage          => [][]any
map[string]json.RawMessage   => map[string]any
[]map[string]json.RawMessage => []map[string]any

The field must have a "caddy" struct tag in this format:

caddy:"key1=val1 key2=val2"

To load modules, a "namespace" key is required. For example, to load modules in the "http.handlers" namespace, you'd put: namespace=http.handlers in the Caddy struct tag.

The module name must also be available. If the field type is a map or slice of maps, then key is assumed to be the module name if an "inline_key" is NOT specified in the caddy struct tag. In this case, the module name does NOT need to be specified in-line with the module itself.

If not a map, or if inline_key is non-empty, then the module name must be embedded into the values, which must be objects; then there must be a key in those objects where its associated value is the module name. This is called the "inline key", meaning the key containing the module's name that is defined inline with the module itself. You must specify the inline key in a struct tag, along with the namespace:

caddy:"namespace=http.handlers inline_key=handler"

This will look for a key/value pair like "handler": "..." in the json.RawMessage in order to know the module name.

To make use of the loaded module(s) (the return value), you will probably want to type-assert each 'any' value(s) to the types that are useful to you and store them on the same struct. Storing them on the same struct makes for easy garbage collection when your host module is no longer needed.

Loaded modules have already been provisioned and validated. Upon returning successfully, this method clears the json.RawMessage(s) in the field since the raw JSON is no longer needed, and this allows the GC to free up memory.

Uses: fmt.Errorf, fmt.Sprintf, json.RawMessage, reflect.Map, reflect.Slice, reflect.TypeOf, reflect.ValueOf, reflect.Zero.

func (Context) LoadModuleByID

LoadModuleByID decodes rawMsg into a new instance of mod and returns the value. If mod.New is nil, an error is returned. If the module implements Validator or Provisioner interfaces, those methods are invoked to ensure the module is fully configured and valid before being used.

This is a lower-level method and will usually not be called directly by most modules. However, this method is useful when dynamically loading/unloading modules in their own context, like from embedded scripts, etc.

Uses: fmt.Errorf, log.Printf, reflect.New, reflect.Ptr, reflect.ValueOf.

func (Context) Logger

Logger returns a logger that is intended for use by the most recent module associated with the context. Callers should not pass in any arguments unless they want to associate with a different module; it panics if more than 1 value is passed in.

Originally, this method's signature was Logger(mod Module), requiring that an instance of a Caddy module be passed in. However, that is no longer necessary, as the closest module most recently associated with the context will be automatically assumed. To prevent a sudden breaking change, this method's signature has been changed to be variadic, but we may remove the parameter altogether in the future. Callers should not pass in any argument. If there is valid need to specify a different module, please open an issue to discuss.

PARTIALLY DEPRECATED: The Logger(module) form is deprecated and may be removed in the future. Do not pass in any arguments.

Uses: zap.NewDevelopment.

func (Context) Module

Module returns the current module, or the most recent one provisioned by the context.

func (Context) Modules

Modules returns the lineage of modules that this context provisioned, with the most recent/current module being last in the list.

func (Context) Slogger

Slogger returns a slog logger that is intended for use by the most recent module associated with the context.

Uses: slog.New, zap.NewDevelopment, zapslog.NewHandler, zapslog.WithName.

func (Context) Storage

Storage returns the configured Caddy storage implementation.

func (DiscardWriter) CaddyModule

CaddyModule returns the Caddy module information.

func (DiscardWriter) OpenWriter

OpenWriter returns io.Discard that can't be closed.

Uses: io.Discard.

func (DiscardWriter) String

func (DiscardWriter) WriterKey

WriterKey returns a unique key representing discard.

func (Event) CloudEvent

CloudEvent exports event e as a structure that, when serialized as JSON, is compatible with the CloudEvents spec.

Uses: json.Marshal.

func (Event) ID

func (Event) Name

func (Event) Origin

func (Event) Timestamp

func (ModuleID) Name

Name returns the Name (last element) of a module ID.

Uses: strings.Split.

func (ModuleID) Namespace

Namespace returns the namespace (or scope) portion of a module ID, which is all but the last label of the ID. If the ID has only one label, then the namespace is empty.

Uses: strings.LastIndex.

func (ModuleInfo) String

func (NetworkAddress) At

At returns a NetworkAddress with a port range of just 1 at the given port offset; i.e. a NetworkAddress that represents precisely 1 address only.

func (NetworkAddress) Expand

Expand returns one NetworkAddress for each port in the port range.

func (NetworkAddress) IsFdNetwork

IsFdNetwork returns true if na.Network is fd or fdgram.

func (NetworkAddress) IsUnixNetwork

IsUnixNetwork returns true if na.Network is unix, unixgram, or unixpacket.

func (NetworkAddress) JoinHostPort

JoinHostPort is like net.JoinHostPort, but where the port is StartPort + offset.

Uses: net.JoinHostPort, strconv.FormatUint.

func (NetworkAddress) Listen

Listen is similar to net.Listen, with a few differences:

Listen announces on the network address using the port calculated by adding portOffset to the start port. (For network types that do not use ports, the portOffset is ignored.)

First Listen checks if a plugin can provide a listener from this address. Otherwise, the provided ListenConfig is used to create the listener. Its Control function, if set, may be wrapped by an internally-used Control function. The provided context may be used to cancel long operations early. The context is not used to close the listener after it has been created.

Caddy's listeners can overlap each other: multiple listeners may be created on the same socket at the same time. This is useful because during config changes, the new config is started while the old config is still running. How this is accomplished varies by platform and network type. For example, on Unix, SO_REUSEPORT is set except on Unix sockets, for which the file descriptor is duplicated and reused; on Windows, the close logic is virtualized using timeouts. Like normal listeners, be sure to Close() them when you are done.

This method returns any type, as the implementations of listeners for various network types are not interchangeable. The type of listener returned is switched on the network type. Stream-based networks ("tcp", "unix", "unixpacket", etc.) return a net.Listener; datagram-based networks ("udp", "unixgram", etc.) return a net.PacketConn; and so forth. The actual concrete types are not guaranteed to be standard, exported types (wrapping is necessary to provide graceful reloads).

Unix sockets will be unlinked before being created, to ensure we can bind to it even if the previous program using it exited uncleanly; it will also be unlinked upon a graceful exit (or when a new config does not use that socket). Listen synchronizes binds to unix domain sockets to avoid race conditions while an existing socket is unlinked.

func (NetworkAddress) ListenAll

ListenAll calls Listen for all addresses represented by this struct, i.e. all ports in the range. (If the address doesn't use ports or has 1 port only, then only 1 listener will be created.) It returns an error if any listener failed to bind, and closes any listeners opened up to that point.

Uses: io.Closer.

func (NetworkAddress) ListenQUIC

ListenQUIC returns a http3.QUICEarlyListener suitable for use in a Caddy module.

The network will be transformed into a QUIC-compatible type if the same address can be used with different networks. Currently this just means that for tcp, udp will be used with the same address instead.

NOTE: This API is EXPERIMENTAL and may be changed or removed.

Uses: http3.ConfigureTLSConfig, net.Addr, net.PacketConn, qlog.DefaultConnectionTracer, rate.NewLimiter, tls.Config.

func (NetworkAddress) PortRangeSize

PortRangeSize returns how many ports are in pa's port range. Port ranges are inclusive, so the size is the difference of start and end ports plus one.

func (NetworkAddress) String

String reconstructs the address string for human display. The output can be parsed by ParseNetworkAddress(). If the address is a unix socket, any non-zero port will be dropped.

func (StderrWriter) CaddyModule

CaddyModule returns the Caddy module information.

func (StderrWriter) OpenWriter

OpenWriter returns os.Stderr that can't be closed.

Uses: os.Stderr.

func (StderrWriter) String

func (StderrWriter) WriterKey

WriterKey returns a unique key representing stderr.

func (StdoutWriter) CaddyModule

CaddyModule returns the Caddy module information.

func (StdoutWriter) OpenWriter

OpenWriter returns os.Stdout that can't be closed.

Uses: os.Stdout.

func (StdoutWriter) String

func (StdoutWriter) WriterKey

WriterKey returns a unique key representing stdout.

func (adminHandler) ServeHTTP

ServeHTTP is the external entry point for API requests. It will only be called once per request.

Uses: net.SplitHostPort, zap.Bool, zap.Int, zap.Reflect, zap.String.

func (deleteListener) Close

func (deletePacketConn) Close

func (deletePacketConn) Unwrap

func (loggableURLArray) MarshalLogArray

func (notClosable) Close

func (writerDestructor) Destruct

Private functions

func changeConfig

changeConfig changes the current config (rawCfg) according to the method, traversed via the given path, and uses the given input as the new value (if applicable; i.e. "DELETE" doesn't have an input). If the resulting config is the same as the previous, no reload will occur unless forceReload is true. If the config is unchanged and not forcefully reloaded, then errConfigUnchanged This function is safe for concurrent use. The ifMatchHeader can optionally be given a string of the format:

"<path> <hash>"

where <path> is the absolute path in the config and <hash> is the expected hash of the config at that path. If the hash in the ifMatchHeader doesn't match the hash of the config, then an APIError with status 412 will be returned.

References: bytes.Equal, fmt.Errorf, hex.EncodeToString, http.MethodConnect, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace, http.StatusBadRequest, http.StatusInternalServerError, http.StatusPreconditionFailed, json.Marshal, json.Unmarshal, strings.Fields.

func decodeBase64DERCert

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

References: base64.StdEncoding, x509.ParseCertificate.

func etagHasher

etagHasher returns a the hasher we used on the config to both produce and verify ETags.

func exitProcess

exitProcess exits the process as gracefully as possible, but it always exits, even if there are errors doing so. It stops all apps, cleans up external locks, removes any PID file, and shuts down admin endpoint(s) in a goroutine. Errors are logged along the way, and an appropriate exit code is emitted.

References: atomic.CompareAndSwapInt32, certmagic.CleanUpOwnLocks, notify.Stopping, os.Exit, os.Remove, zap.Error, zap.Int, zap.String.

func exitProcessFromSignal

exitProcessFromSignal exits the process from a system signal.

References: context.TODO, zap.String.

func fakeClosedErr

fakeClosedErr returns an error value that is not temporary nor a timeout, suitable for making the caller think the listener is actually closed

References: net.OpError.

func finishSettingUp

finishSettingUp should be run after all apps have successfully started.

References: errors.Is, fmt.Errorf, http.MethodPost, time.Duration, time.NewTimer, zap.Error, zap.Int, zap.String.

func getListenerFromPlugin

getListenerFromPlugin returns a listener on the given network and address if a plugin has registered the network name. It may return (nil, nil) if no plugin can provide a listener.

References: zap.String.

func getModuleNameInline

getModuleNameInline loads the string value from raw of moduleNameKey, where raw must be a JSON encoding of a map. It returns that value, along with the result of removing that key from raw.

References: fmt.Errorf, json.Marshal, json.Unmarshal.

func handleConfig

References: bytes.Buffer, errors.Is, fmt.Errorf, http.MethodDelete, http.MethodGet, http.MethodPatch, http.MethodPost, http.MethodPut, http.StatusBadRequest, http.StatusInternalServerError, http.StatusMethodNotAllowed, io.Copy, io.MultiWriter, strings.Contains.

func handleConfigID

References: fmt.Errorf, http.StatusBadRequest, http.StatusNotFound, path.Join, strings.Split.

func handleStop

References: context.Background, fmt.Errorf, http.MethodPost, http.StatusMethodNotAllowed.

func homeDirUnsafe

homeDirUnsafe is a low-level function that returns the user's home directory from environment variables. Careful: if it cannot be determined, an empty string is returned. If not accounting for that case, use HomeDir() instead; otherwise you may end up using the root of the file system.

References: os.Getenv, runtime.GOOS.

func indexConfigObjects

indexConfigObjects recursively searches ptr for object fields named "@id" and maps that ID value to the full configPath in the index. This function is NOT safe for concurrent access; obtain a write lock on currentCtxMu.

References: fmt.Errorf, fmt.Sprintf, path.Join, strconv.Itoa.

func init

References: os.LookupEnv.

func instrumentHandlerCounter

Similar to promhttp.InstrumentHandlerCounter, but upper-cases method names instead of lower-casing them.

Unlike promhttp.InstrumentHandlerCounter, this assumes a "code" and "method" label is present, and will panic otherwise.

References: http.HandlerFunc, http.Request, http.ResponseWriter, metrics.SanitizeCode, metrics.SanitizeMethod, prometheus.Labels.

func isJSONRawMessage

isJSONRawMessage returns true if the type is encoding/json.RawMessage.

func isModuleMapType

isModuleMapType returns true if the type is map[string]json.RawMessage. It assumes that the string key is the module name, but this is not always the case. To know for sure, this function must return true, but also the struct tag where this type appears must NOT define an inline_key attribute, which would mean that the module names appear inline with the values, not in the key.

References: reflect.Map, reflect.String.

func listenReusable

listenReusable creates a new listener for the given network and address, and adds it to listenerPool.

References: fmt.Errorf, io.Closer, net.FileListener, net.FilePacketConn, net.Listener, net.PacketConn, net.UnixConn, net.UnixListener, os.File, os.NewFile, slices.Contains, strconv.IntSize, strconv.ParseUint, syscall.RawConn.

func listenerKey

func makeEtag

makeEtag returns an Etag header value (including quotes) for the given config path and hash of contents at that path.

References: fmt.Sprintf.

func manageIdentity

manageIdentity sets up automated identity management for this server.

References: certmagic.Config, certmagic.Issuer, fmt.Errorf, json.RawMessage.

func newDefaultProductionLog

newDefaultProductionLog configures a custom log that is intended for use by default if no other log is specified in a config. It writes to stderr, uses the console encoder, and enables INFO-level logs and higher.

References: zap.New, zap.RedirectStdLog, zapcore.InfoLevel.

func newDefaultProductionLogEncoder

References: os.Stderr, term.IsTerminal, time.Time, zap.NewProductionEncoderConfig, zapcore.CapitalColorLevelEncoder, zapcore.NewConsoleEncoder, zapcore.NewJSONEncoder, zapcore.PrimitiveArrayEncoder.

func newDelegator

func newSharedQUICState

newSharedQUICState creates a new sharedQUICState

References: tls.Config.

func parseAdminListenAddr

parseAdminListenAddr extracts a singular listen address from either addr or defaultAddr, returning the network and the address of the listener.

References: fmt.Errorf.

func parseLevel

References: fmt.Errorf, strings.ToLower, zapcore.DebugLevel, zapcore.ErrorLevel, zapcore.FatalLevel, zapcore.InfoLevel, zapcore.PanicLevel, zapcore.WarnLevel.

func provisionContext

provisionContext creates a new context from the given configuration and provisions storage and apps. If newCfg is nil a new empty configuration will be created. If replaceAdminServer is true any currently active admin server will be replaced with a new admin server based on the provided configuration.

References: certmagic.Default, context.Background, filesystems.FileSystemMap, fmt.Errorf.

func readConfig

readConfig traverses the current config to path and writes its JSON encoding to out.

References: http.MethodGet.

func readFileIntoBuffer

readFileIntoBuffer reads the file at filePath into a size limited buffer.

References: io.EOF, os.Open.

func replaceLocalAdminServer

replaceLocalAdminServer replaces the running local admin server according to the relevant configuration in cfg. If no configuration for the admin endpoint exists in cfg, a default one is used, so that there is always an admin server (unless it is explicitly configured to be disabled). Critically note that some elements and functionality of the context may not be ready, e.g. storage. Tread carefully.

References: context.TODO, errors.Is, http.ErrServerClosed, http.Server, net.ListenConfig, net.Listener, time.Second, zap.Array, zap.Bool, zap.Error, zap.String.

func replaceRemoteAdminServer

replaceRemoteAdminServer replaces the running remote admin server according to the relevant configuration in cfg. It stops any previous remote admin server and only starts a new one if configured.

References: errors.Is, fmt.Errorf, http.ErrServerClosed, http.Server, net.ListenConfig, net.Listener, time.Second, tls.NewListener, tls.RequireAndVerifyClientCert, x509.NewCertPool, zap.DebugLevel, zap.Error, zap.NewStdLogAt, zap.String.

func reusePort

reusePort sets SO_REUSEPORT. Ineffective for unix sockets.

References: unix.SOL_SOCKET, unix.SetsockoptInt, zap.Error, zap.String, zap.Uintptr.

func reuseUnixSocket

reuseUnixSocket copies and reuses the unix domain socket (UDS) if we already have it open; if not, unlink it so we can have it. No-op if not a unix network.

References: atomic.AddInt32, errors.Is, fs.ErrNotExist, net.FileListener, net.FilePacketConn, net.UnixConn, net.UnixListener, syscall.Unlink.

func run

run runs newCfg and starts all its apps if start is true. If any errors happen, cleanup is performed if any modules were provisioned; apps that were started already will be stopped, so this function should not leak resources if an error is returned. However, if no error is returned and start == false, you should cancel the config if you are not going to start it, so that each provisioned module will be cleaned up.

This is a low-level function; most callers will want to use Run instead, which also updates the config's raw state.

References: fmt.Errorf.

func stopAdminServer

References: context.Background, context.WithTimeout, fmt.Errorf, time.Second, zap.String.

func trapSignalsCrossPlatform

trapSignalsCrossPlatform captures SIGINT or interrupt (depending on the OS), which initiates a graceful shutdown. A second SIGINT or interrupt will forcefully exit the process immediately.

References: os.Exit, os.Interrupt, os.Signal, signal.Notify, zap.String.

func trapSignalsPosix

trapSignalsPosix captures POSIX-only signals.

References: certmagic.CleanUpOwnLocks, context.TODO, os.Exit, os.Signal, signal.Ignore, signal.Notify, syscall.SIGHUP, syscall.SIGPIPE, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGUSR1, syscall.SIGUSR2, zap.String.

func unsyncedConfigAccess

unsyncedConfigAccess traverses into the current config and performs the operation at path according to method, using body and out as needed. This is a low-level, unsynchronized function; most callers will want to use changeConfig or readConfig instead. This requires a read or write lock on currentCtxMu, depending on method (GET needs only a read lock; all others need a write lock).

References: fmt.Errorf, http.MethodDelete, http.MethodGet, http.MethodPatch, http.MethodPost, http.MethodPut, http.StatusConflict, http.StatusNotFound, json.NewEncoder, json.Unmarshal, strconv.Atoi, strings.Join, strings.Split, strings.Trim.

func unsyncedDecodeAndRun

unsyncedDecodeAndRun removes any meta fields (like @id tags) from cfgJSON, decodes the result into a *Config, and runs it as the new config, replacing any other current config. It does NOT update the raw config state, as this is a lower-level function; most callers will want to use Load instead. A write lock on rawCfgMu is required! If allowPersist is false, it will not be persisted to disk, even if it is configured to.

References: filepath.Dir, fmt.Errorf, os.MkdirAll, os.WriteFile, zap.Error, zap.String.

func unsyncedStop

unsyncedStop stops ctx from running, but has no locking around ctx. It is a no-op if ctx has a nil cfg. If any app returns an error when stopping, it is logged and the function continues stopping the next app. This function assumes all apps in ctx were successfully started first.

A lock on rawCfgMu is required, even though this function does not access rawCfg, that lock synchronizes the stop/start of apps.

References: log.Printf.

func newAdminHandler

newAdminHandler reads admin's config and returns an http.Handler suitable for use in an admin endpoint server, which will be listening on listenAddr.

References: expvar.Handler, http.Handler, http.HandlerFunc, http.NewServeMux, http.Request, http.ResponseWriter, pprof.Cmdline, pprof.Index, pprof.Profile, pprof.Symbol, pprof.Trace, prometheus.Labels, strings.ToUpper.

func provisionAdminRouters

provisionAdminRouters provisions all the router modules in the admin.api namespace that need provisioning.

func buildCore

References: time.Second, zapcore.AddSync, zapcore.NewCore, zapcore.NewNopCore, zapcore.NewSamplerWithOptions.

func buildOptions

References: fmt.Errorf, zap.AddCaller, zap.AddCallerSkip, zap.AddStacktrace, zap.Option.

func provisionCommon

References: fmt.Errorf, zapcore.Core, zapcore.Encoder, zapcore.NewTee.

func initMetrics

References: collectors.NewBuildInfoCollector, collectors.NewGoCollector, collectors.NewProcessCollector, collectors.ProcessCollectorOpts.

func loggerAllowed

loggerAllowed returns true if name is allowed to emit to cl. isModule should be true if name is the name of a module and you want to see if ANY of that module's logs would be permitted.

References: strings.HasPrefix.

func matchesModule

func provision

References: fmt.Errorf, slices.Contains, strings.HasPrefix.

func certmagicConfig

References: certmagic.CacheOptions, certmagic.Certificate, certmagic.Config, certmagic.New, certmagic.NewCache.

func closeLogs

closeLogs cleans up resources allocated during openLogs. A successful call to openLogs calls this automatically when the context is canceled.

References: log.Printf.

func openLogs

openLogs sets up the config and opens all the configured writers. It closes its logs when ctx is canceled, so it should clean up after itself.

References: fmt.Errorf, zap.Error.

func openWriter

openWriter opens a writer using opener, and returns true if the writer is new, or false if the writer already exists.

References: io.WriteCloser.

func setupNewDefault

References: fmt.Errorf, zap.New, zap.String.

func fromStatic

fromStatic provides values from r.static.

func replace

References: fmt.Errorf, strings.Builder, strings.Contains, strings.Index.

func provision

References: zap.New, zap.RedirectStdLog.

func addState

addState adds tls.Config and activeRequests to the map if not present and returns the corresponding context and its cancelFunc so that when cancelled, the active tls.Config will change

References: context.Background, context.WithCancel, zap.Int.

func getConfigForClient

getConfigForClient is used as tls.Config's GetConfigForClient field

func allowedOrigins

allowedOrigins returns a list of origins that are allowed. If admin.Origins is nil (null), the provided listen address will be used as the default origin. If admin.Origins is empty, no origins will be allowed, effectively bricking the endpoint for non-unix-socket endpoints, but whatever.

References: net.JoinHostPort, strings.Contains, url.Parse, url.URL.

func emitEvent

emitEvent is a small convenience method so the caddy core can emit events, if the event app is configured.

func loadModuleInline

loadModuleInline loads a module from a JSON raw message which decodes to a map[string]any, where one of the object keys is moduleNameKey and the corresponding value is the module name (as a string) which can be found in the given scope. In other words, the module name is declared in-line with the module itself.

This allows modules to be decoded into their concrete types and used when their names cannot be the unique key in a map, such as when there are multiple instances in the map or it appears in an array (where there are no custom keys). In other words, the key containing the module name is treated special/separate from all the other keys in the object.

References: fmt.Errorf.

func loadModuleMap

loadModuleMap loads modules from a ModuleMap, i.e. map[string]any, where the key is the module name. With a module map, module names do not need to be defined inline with their values.

References: fmt.Errorf, json.RawMessage.

func loadModulesFromRegularMap

loadModulesFromRegularMap loads modules from val, where val is a map[string]json.RawMessage. Map keys are NOT interpreted as module names, so module names are still expected to appear inline with the objects.

References: fmt.Errorf, json.RawMessage.

func loadModulesFromSomeMap

loadModulesFromSomeMap loads modules from val, which must be a type of map[string]any. Depending on inlineModuleKey, it will be interpreted as either a ModuleMap (key is the module name) or as a regular map (key is not the module name, and module name is defined inline).

References: fmt.Sprintf.

func isLoopback

References: netip.ParseAddr.

func isWildcardInterface

References: netip.ParseAddr.

func listen

References: fmt.Errorf, fs.FileMode, os.Chmod, strings.HasPrefix.

func port

References: fmt.Sprintf, strconv.FormatUint.

func enforceAccessControls

enforceAccessControls enforces application-layer access controls for r based on remote. It expects that the TLS server has already established at least one verified chain of trust, and then looks for a matching, authorized public key that is allowed to access the defined path(s) using the defined method(s).

References: crypto.PublicKey, http.StatusForbidden, http.StatusUnauthorized, slices.Contains, strings.HasPrefix.

func replace

func checkHost

checkHost returns a handler that wraps next such that it will only be called if the request's Host header matches a trustworthy/expected value. This helps to mitigate DNS rebinding attacks.

References: fmt.Errorf, http.StatusForbidden, slices.ContainsFunc, url.URL.

func checkOrigin

checkOrigin ensures that the Origin header, if set, matches the intended target; prevents arbitrary sites from issuing requests to our listener. It returns the origin that was obtained from r.

References: fmt.Errorf, http.StatusForbidden.

func getOrigin

References: url.Parse.

func handleError

References: http.StatusInternalServerError, json.NewEncoder, zap.Error, zap.Int.

func originAllowed

func serveHTTP

serveHTTP is the internal entry point for API requests. It may be called more than once per request, for example if a request is rewritten (i.e. internal redirect).

References: fmt.Errorf, http.MethodOptions, strings.Contains.

func replace

References: bytes.TrimSuffix, os.Getwd, strings.HasPrefix, zap.Error, zap.String.

func replace

References: filepath.Separator, http.TimeFormat, os.Getenv, os.Getwd, os.Hostname, runtime.GOARCH, runtime.GOOS, strconv.FormatInt, strconv.Itoa, strings.HasPrefix, time.Millisecond.


Tests

Files: 7. Third party imports: 2. Imports from organisation: 1. Tests: 28. Benchmarks: 2.

Vars

Types

fooModule

This type doesn't have documentation.

Field name Field type Comment
IntField

int

No comment on field.
StrField

string

No comment on field.

mockIssuer

This type doesn't have documentation.

Field name Field type Comment
configSet

*certmagic.Config

No comment on field.

mockIssuerModule

This type doesn't have documentation.

Field name Field type Comment

*mockIssuer

No comment on field.

mockModule

This type doesn't have documentation.

Field name Field type Comment

mockRouter

No comment on field.

mockProvisionableModule

This type doesn't have documentation.

Field name Field type Comment

*mockProvisionableRouter

No comment on field.

mockProvisionableRouter

This type doesn't have documentation.

Field name Field type Comment

mockRouter

No comment on field.
provisionErr

error

No comment on field.
provisioned

bool

No comment on field.

mockRouter

This type doesn't have documentation.

Field name Field type Comment
routes

[]AdminRoute

No comment on field.

Test functions

TestAdminHandlerBuiltinRouteErrors

References: fmt.Sprintf, http.MethodGet, http.MethodPost, http.StatusBadRequest, http.StatusMethodNotAllowed, httptest.NewRecorder, httptest.NewRequest, testing.T.

TestAdminHandlerErrorHandling

References: fmt.Errorf, http.HandlerFunc, http.MethodGet, http.NewServeMux, http.Request, http.ResponseWriter, http.StatusOK, httptest.NewRecorder, httptest.NewRequest, json.NewDecoder.

TestAdminRouterProvisioning

References: fmt.Errorf, http.Request, http.ResponseWriter, maps.Copy, testing.T.

TestAllowedOriginsUnixSocket

References: reflect.DeepEqual, testing.T.

TestCustomLog_loggerAllowed

References: testing.T.

TestETags

References: fmt.Sprintf, http.MethodPost, http.StatusPreconditionFailed.

TestExpand

References: reflect.DeepEqual.

TestGetModules

References: reflect.DeepEqual.

TestJoinHostPort

TestJoinNetworkAddress

TestLoadConcurrent

References: sync.WaitGroup.

TestManageIdentity

References: certmagic.FileStorage, context.Background, json.RawMessage, maps.Copy, testing.T.

TestModuleID

TestNewAdminHandlerRouterRegistration

References: http.Request, http.ResponseWriter, http.StatusOK, httptest.NewRecorder, httptest.NewRequest, maps.Copy.

TestParseDuration

References: time.Duration, time.Hour, time.Minute, time.Second.

TestParseNetworkAddress

References: reflect.DeepEqual.

TestParseNetworkAddressWithDefaults

References: reflect.DeepEqual.

TestReplaceRemoteAdminServer

References: certmagic.CacheOptions, certmagic.Certificate, certmagic.Config, certmagic.FileStorage, certmagic.NewCache, context.Background, testing.T.

TestReplacer

TestReplacerDelete

References: sync.RWMutex.

TestReplacerMap

References: fmt.Sprintf.

TestReplacerNew

References: filepath.Separator, os.Getwd, os.Hostname, os.Setenv, runtime.GOARCH, runtime.GOOS.

TestReplacerNewWithoutFile

References: runtime.GOOS.

TestReplacerReplaceKnown

References: sync.RWMutex.

TestReplacerSet

TestSplitNetworkAddress

TestSplitUnixSocketPermissionsBits

TestUnsyncedConfigAccess

References: json.Unmarshal, reflect.DeepEqual.

Benchmark functions

BenchmarkLoad

BenchmarkReplacer

References: testing.B.