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

const DefaultLoggerName = "default"
// ImportPath is the package import path for Caddy core.
// This identifier may be removed in the future.
const ImportPath = "github.com/caddyserver/caddy/v2"
// ReplacerCtxKey is the context key for a replacer.
const ReplacerCtxKey CtxKey = "replacer"
const (
	rawConfigKey	= "config"
	idKey		= "@id"
)
const phOpen, phClose, phEscape = '{', '}', '\\'
// Exit codes. Generally, you should NOT
// automatically restart the process if the
// exit code is ExitCodeFailedStartup (1).
const (
	ExitCodeSuccess	= iota
	ExitCodeFailedStartup
	ExitCodeForceQuit
	ExitCodeFailedQuit
)
const filePrefix = "file."
const maxPortSpan = 65535
const unixSOREUSEPORT = unix.SO_REUSEPORT

Vars

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

var ConfigAutosavePath = filepath.Join(AppConfigDir(), "autosave.json")

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.

var CustomVersion string

DefaultStorage is Caddy's default storage module.

var DefaultStorage = &certmagic.FileStorage{Path: AppDataDir()}

ErrNotConfigured indicates a module is not configured.

var ErrNotConfigured = fmt.Errorf("module not configured")
var (
	exitFuncs	[]func(context.Context)
	exitFuncsMu	sync.Mutex
)
var (
	serverMu				sync.Mutex
	localAdminServer, remoteAdminServer	*http.Server
	identityCertCache			*certmagic.Cache
)
var (
	// currentCtx is the root context for the currently-running
	// configuration, which can be accessed through this value.
	// If the Config contained in this value is not nil, then
	// a config is currently active/running.
	currentCtx	Context
	currentCtxMu	sync.RWMutex

	// rawCfg is the current, generic-decoded configuration;
	// we initialize it as a map with one field ("config")
	// to maintain parity with the API endpoint and to avoid
	// the special case of having to access/mutate the variable
	// directly without traversing into it.
	rawCfg	= map[string]any{
		rawConfigKey: nil,
	}

	// rawCfgJSON is the JSON-encoded form of rawCfg. Keeping
	// this around avoids an extra Marshal call during changes.
	rawCfgJSON	[]byte

	// rawCfgIndex is the map of user-assigned ID to expanded
	// path, for converting /id/ paths to /config/ paths.
	rawCfgIndex	map[string]string

	// rawCfgMu protects all the rawCfg fields and also
	// essentially synchronizes config changes/reloads.
	rawCfgMu	sync.RWMutex
)
var (
	// DefaultAdminListen is the address for the local admin
	// listener, if none is specified at startup.
	DefaultAdminListen	= "localhost:2019"

	// DefaultRemoteAdminListen is the address for the remote
	// (TLS-authenticated) admin listener, if enabled and not
	// specified otherwise.
	DefaultRemoteAdminListen	= ":2021"
)
var wd, wderr = os.Getwd()
var (
	modules		= make(map[string]ModuleInfo)
	modulesMu	sync.RWMutex
)
var (
	coloringEnabled		= os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "xterm-mono"
	defaultLogger, _	= newDefaultProductionLog()
	defaultLoggerMu		sync.RWMutex
)

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

var adminMetrics = struct {
	requestCount	*prometheus.CounterVec
	requestErrors	*prometheus.CounterVec
}{}
var bufPool = sync.Pool{
	New: func() any {
		return new(bytes.Buffer)
	},
}

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

var bufferPool = sync.Pool{
	New: func() any {
		return new(bytes.Buffer)
	},
}

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.

var errFakeClosed = fmt.Errorf("listener 'closed' 😉")

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.

var errInternalRedir = fmt.Errorf("internal redirect; re-authorization required")

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.

var errSameConfig = errors.New("config is unchanged")
var exiting = new(int32)	// accessed atomically

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

var globalMetrics = struct {
	configSuccess		prometheus.Gauge
	configSuccessTime	prometheus.Gauge
}{}

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.

var idRegexp = regexp.MustCompile(`(?m),?\s*"` + idKey + `"\s*:\s*(-?[0-9]+(\.[0-9]+)?|(?U)".*")\s*,?`)

listenerPool stores and allows reuse of active listeners.

var listenerPool = NewUsagePool()
var networkTypes = map[string]ListenerFunc{}

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

var nowFunc = time.Now

pidfile is the name of the pidfile, if any.

var pidfile string

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

var socketFiles = map[uintptr]*os.File{}

socketFilesMu synchronizes socketFiles insertions

var socketFilesMu sync.Mutex

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

var unixSockets = make(map[string]interface {
	File() (*os.File, error)
})
var unixSocketsMu sync.Mutex
var writers = NewUsagePool()

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.

type APIError struct {
	HTTPStatus	int	`json:"-"`
	Err		error	`json:"-"`
	Message		string	`json:"error"`
}

AdminAccess

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

type AdminAccess struct {
	// 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.
	PublicKeys	[]string	`json:"public_keys,omitempty"`

	// Limits what the associated identities are allowed to do.
	// If unspecified, all permissions are granted.
	Permissions	[]AdminPermissions	`json:"permissions,omitempty"`

	publicKeys	[]crypto.PublicKey
}

AdminConfig

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

type AdminConfig struct {
	// 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.
	Disabled	bool	`json:"disabled,omitempty"`

	// 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.
	Listen	string	`json:"listen,omitempty"`

	// 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.
	EnforceOrigin	bool	`json:"enforce_origin,omitempty"`

	// 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.
	Origins	[]string	`json:"origins,omitempty"`

	// Options pertaining to configuration management.
	Config	*ConfigSettings	`json:"config,omitempty"`

	// 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.
	Identity	*IdentityConfig	`json:"identity,omitempty"`

	// 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.
	Remote	*RemoteAdmin	`json:"remote,omitempty"`

	// Holds onto the routers so that we can later provision them
	// if they require provisioning.
	routers	[]AdminRouter
}

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.

type AdminHandler interface {
	ServeHTTP(http.ResponseWriter, *http.Request) error
}

AdminHandlerFunc

AdminHandlerFunc is a convenience type like http.HandlerFunc.

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

AdminPermissions

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

type AdminPermissions struct {
	// The API paths allowed. Paths are simple prefix matches.
	// Any subpath of the specified paths will be allowed.
	Paths	[]string	`json:"paths,omitempty"`

	// The HTTP methods allowed for the given paths.
	Methods	[]string	`json:"methods,omitempty"`
}

AdminRoute

AdminRoute represents a route for the admin endpoint.

type AdminRoute struct {
	Pattern	string
	Handler	AdminHandler
}

AdminRouter

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

type AdminRouter interface {
	Routes() []AdminRoute
}

App

App is a thing that Caddy runs.

type App interface {
	Start() error
	Stop() error
}

BaseLog

BaseLog contains the common logging parameters for logging.

type BaseLog struct {
	// The module that writes out log entries for the sink.
	WriterRaw	json.RawMessage	`json:"writer,omitempty" caddy:"namespace=caddy.logging.writers inline_key=output"`

	// The encoder is how the log entries are formatted or encoded.
	EncoderRaw	json.RawMessage	`json:"encoder,omitempty" caddy:"namespace=caddy.logging.encoders inline_key=format"`

	// Tees entries through a zap.Core module which can extract
	// log entry metadata and fields for further processing.
	CoreRaw	json.RawMessage	`json:"core,omitempty" caddy:"namespace=caddy.logging.cores inline_key=module"`

	// Level is the minimum level to emit, and is inclusive.
	// Possible levels: DEBUG, INFO, WARN, ERROR, PANIC, and FATAL
	Level	string	`json:"level,omitempty"`

	// 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.
	Sampling	*LogSampling	`json:"sampling,omitempty"`

	// If true, the log entry will include the caller's
	// file name and line number. Default off.
	WithCaller	bool	`json:"with_caller,omitempty"`

	// If non-zero, and `with_caller` is true, this many
	// stack frames will be skipped when determining the
	// caller. Default 0.
	WithCallerSkip	int	`json:"with_caller_skip,omitempty"`

	// 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.
	WithStacktrace	string	`json:"with_stacktrace,omitempty"`

	writerOpener	WriterOpener
	writer		io.WriteCloser
	encoder		zapcore.Encoder
	levelEnabler	zapcore.LevelEnabler
	core		zapcore.Core
}

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.

type CleanerUpper interface {
	Cleanup() error
}

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).

type Config struct {
	Admin	*AdminConfig	`json:"admin,omitempty"`
	Logging	*Logging	`json:"logging,omitempty"`

	// 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](/docs/conventions#data-directory).
	StorageRaw	json.RawMessage	`json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"`

	// 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.
	AppsRaw	ModuleMap	`json:"apps,omitempty" caddy:"namespace="`

	apps	map[string]App
	storage	certmagic.Storage

	cancelFunc	context.CancelFunc

	// filesystems is a dict of filesystems that will later be loaded from and added to.
	filesystems	FileSystems
}

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.

type ConfigLoader interface {
	LoadConfig(Context) ([]byte, error)
}

ConfigSettings

ConfigSettings configures the management of configuration.

type ConfigSettings struct {
	// 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.
	Persist	*bool	`json:"persist,omitempty"`

	// 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.
	LoadRaw	json.RawMessage	`json:"load,omitempty" caddy:"namespace=caddy.config_loaders inline_key=module"`

	// 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.
	LoadDelay	Duration	`json:"load_delay,omitempty"`
}

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.

type ConfiguresFormatterDefault interface {
	ConfigureDefaultFormat(WriterOpener) error
}

Constructor

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

type Constructor func() (Destructor, error)

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).

type Context struct {
	context.Context

	moduleInstances	map[string][]Module
	cfg		*Config
	ancestry	[]Module
	cleanupFuncs	[]func()		// invoked at every config unload
	exitFuncs	[]func(context.Context)	// invoked at config unload ONLY IF the process is exiting (EXPERIMENTAL)
	metricsRegistry	*prometheus.Registry
}

CtxKey

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

type CtxKey string

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.

type CustomLog struct {
	BaseLog

	// 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".
	Include	[]string	`json:"include,omitempty"`

	// 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".
	Exclude	[]string	`json:"exclude,omitempty"`
}

Destructor

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

type Destructor interface {
	Destruct() error
}

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.

type Duration time.Duration

FileSystems

This type doesn't have documentation.

type FileSystems interface {
	Register(k string, v fs.FS)
	Unregister(k string)
	Get(k string) (v fs.FS, ok bool)
	Default() fs.FS
}

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).

type IdentityConfig struct {
	// 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.
	Identifiers	[]string	`json:"identifiers,omitempty"`

	// 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.
	IssuersRaw	[]json.RawMessage	`json:"issuers,omitempty" caddy:"namespace=tls.issuance inline_key=module"`

	issuers	[]certmagic.Issuer
}

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.

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

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.

type ListenerWrapper interface {
	WrapListener(net.Listener) net.Listener
}

LogSampling

LogSampling configures log entry sampling.

type LogSampling struct {
	// The window over which to conduct sampling.
	Interval	time.Duration	`json:"interval,omitempty"`

	// Log this many entries within a given level and
	// message for each interval.
	First	int	`json:"first,omitempty"`

	// 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.
	Thereafter	int	`json:"thereafter,omitempty"`
}

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.

type Logging struct {
	// 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.
	Sink	*SinkLog	`json:"sink,omitempty"`

	// 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.
	Logs	map[string]*CustomLog	`json:"logs,omitempty"`

	// 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
	writerKeys	[]string
}

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.

type Module interface {
	// This method indicates that the type is a Caddy
	// module. The returned ModuleInfo must have both
	// a name and a constructor function. This method
	// must not have any side-effects.
	CaddyModule() ModuleInfo
}

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

type ModuleID string

ModuleInfo

ModuleInfo represents a registered Caddy module.

type ModuleInfo struct {
	// ID is the "full name" of the module. It
	// must be unique and properly namespaced.
	ID	ModuleID

	// 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).
	New	func() Module
}

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.

type ModuleMap map[string]json.RawMessage

NetworkAddress

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

type NetworkAddress struct {
	// Should be a network value accepted by Go's net package or
	// by a plugin providing a listener for that network type.
	Network	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.
	Host	string

	// 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.
	StartPort	uint
	EndPort		uint
}

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.

type Provisioner interface {
	Provision(Context) error
}

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.

type RemoteAdmin struct {
	// The address on which to start the secure listener. Accepts placeholders.
	// Default: :2021
	Listen	string	`json:"listen,omitempty"`

	// 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.
	AccessControl	[]*AdminAccess	`json:"access_control,omitempty"`
}

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.

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

Replacer

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

type Replacer struct {
	providers	[]replacementProvider
	static		map[string]any
	mapMutex	*sync.RWMutex
}

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.

type ReplacerFunc func(key string) (any, bool)

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.

type SinkLog struct {
	BaseLog
}

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.

type StorageConverter interface {
	CertMagicStorage() (certmagic.Storage, error)
}

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.

type UsagePool struct {
	sync.RWMutex
	pool	map[any]*usagePoolVal
}

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.

type Validator interface {
	Validate() error
}

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.

type WriterOpener interface {
	fmt.Stringer

	// WriterKey is a string that uniquely identifies this
	// writer configuration. It is not shown to humans.
	WriterKey() string

	// OpenWriter opens a log for writing. The writer
	// should be safe for concurrent use but need not
	// be synchronous.
	OpenWriter() (io.WriteCloser, error)
}

StdoutWriter, StderrWriter, DiscardWriter

This type doesn't have documentation.

type (
	// StdoutWriter writes logs to standard out.
	StdoutWriter	struct{}

	// StderrWriter writes logs to standard error.
	StderrWriter	struct{}

	// DiscardWriter discards all writes.
	DiscardWriter	struct{}
)

adminHandler

This type doesn't have documentation.

type adminHandler struct {
	mux	*http.ServeMux

	// security for local/plaintext endpoint
	enforceOrigin	bool
	enforceHost	bool
	allowedOrigins	[]*url.URL

	// security for remote/encrypted endpoint
	remoteControl	*RemoteAdmin
}

contextAndCancelFunc

contextAndCancelFunc groups context and its cancelFunc

type contextAndCancelFunc struct {
	context.Context
	context.CancelFunc
}

defaultCustomLog

This type doesn't have documentation.

type defaultCustomLog struct {
	*CustomLog
	logger	*zap.Logger
}

delegator

This type doesn't have documentation.

type delegator struct {
	http.ResponseWriter
	status	int
}

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).

type deleteListener struct {
	net.Listener
	lnKey	string
}

deletePacketConn

deletePacketConn is like deleteListener, but for net.PacketConns.

type deletePacketConn struct {
	net.PacketConn
	lnKey	string
}

fakeCloseQuicListener

This type doesn't have documentation.

type fakeCloseQuicListener struct {
	closed			int32	// accessed atomically; belongs to this struct only
	*sharedQuicListener		// embedded, so we also become a quic.EarlyListener
	context			context.Context
	contextCancel		context.CancelFunc
}

fileReplacementProvider

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

type fileReplacementProvider struct{}

filteringCore

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

type filteringCore struct {
	zapcore.Core
	cl	*CustomLog
}

globalDefaultReplacementProvider

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

type globalDefaultReplacementProvider struct{}

loggableURLArray

This type doesn't have documentation.

type loggableURLArray []*url.URL

notClosable

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

type notClosable struct{ io.Writer }

replacementProvider

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

type replacementProvider interface {
	replace(key string) (any, bool)
}

sharedQUICState

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

type sharedQUICState struct {
	rmu		sync.RWMutex
	tlsConfs	map[*tls.Config]contextAndCancelFunc
	activeTlsConf	*tls.Config
}

sharedQuicListener

sharedQuicListener is like sharedListener, but for quic.EarlyListeners.

type sharedQuicListener struct {
	*quic.EarlyListener
	packetConn	net.PacketConn	// we have to hold these because quic-go won't close listeners it didn't create
	sqs		*sharedQUICState
	key		string
}

unixConn

This type doesn't have documentation.

type unixConn struct {
	*net.UnixConn
	mapKey	string
	count	*int32	// accessed atomically
}

unixListener

This type doesn't have documentation.

type unixListener struct {
	*net.UnixListener
	mapKey	string
	count	*int32	// accessed atomically
}

usagePoolVal

This type doesn't have documentation.

type usagePoolVal struct {
	refs	int32	// accessed atomically; must be 64-bit aligned for 32-bit systems
	value	any
	err	error
	sync.RWMutex
}

writerDestructor

This type doesn't have documentation.

type writerDestructor struct {
	io.WriteCloser
}

Functions

func ActiveContext

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

func ActiveContext() Context {
	currentCtxMu.RLock()
	defer currentCtxMu.RUnlock()
	return currentCtx
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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

func AppConfigDir() string {
	if basedir := os.Getenv("XDG_CONFIG_HOME"); basedir != "" {
		return filepath.Join(basedir, "caddy")
	}
	basedir, err := os.UserConfigDir()
	if err != nil {
		Log().Warn("unable to determine directory for user configuration; falling back to current directory", zap.Error(err))
		return "./caddy"
	}
	subdir := "caddy"
	switch runtime.GOOS {
	case "windows", "darwin":
		subdir = "Caddy"
	}
	return filepath.Join(basedir, subdir)
}

Cognitive complexity: 7, Cyclomatic complexity: 5

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

func AppDataDir() string {
	if basedir := os.Getenv("XDG_DATA_HOME"); basedir != "" {
		return filepath.Join(basedir, "caddy")
	}
	switch runtime.GOOS {
	case "windows":
		appData := os.Getenv("AppData")
		if appData != "" {
			return filepath.Join(appData, "Caddy")
		}
	case "darwin":
		home := homeDirUnsafe()
		if home != "" {
			return filepath.Join(home, "Library", "Application Support", "Caddy")
		}
	case "plan9":
		home := homeDirUnsafe()
		if home != "" {
			return filepath.Join(home, "lib", "caddy")
		}
	case "android":
		home := homeDirUnsafe()
		if home != "" {
			return filepath.Join(home, "caddy")
		}
	default:
		home := homeDirUnsafe()
		if home != "" {
			return filepath.Join(home, ".local", "share", "caddy")
		}
	}
	return "./caddy"
}

Cognitive complexity: 18, Cyclomatic complexity: 12

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

func Exiting

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

func Exiting() bool	{ return atomic.LoadInt32(exiting) == 1 }

Cognitive complexity: 0, Cyclomatic complexity: 1

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.

func FastAbs(path string) (string, error) {
	if filepath.IsAbs(path) {
		return filepath.Clean(path), nil
	}
	if wderr != nil {
		return "", wderr
	}
	return filepath.Join(wd, path), nil
}

Cognitive complexity: 4, Cyclomatic complexity: 3

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

func GetModule

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

func GetModule(name string) (ModuleInfo, error) {
	modulesMu.RLock()
	defer modulesMu.RUnlock()
	m, ok := modules[name]
	if !ok {
		return ModuleInfo{}, fmt.Errorf("module not registered: %s", name)
	}
	return m, nil
}

Cognitive complexity: 3, Cyclomatic complexity: 2

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 GetModuleID(instance any) string {
	var id string
	if mod, ok := instance.(Module); ok {
		id = string(mod.CaddyModule().ID)
	}
	return id
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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 GetModuleName(instance any) string {
	var name string
	if mod, ok := instance.(Module); ok {
		name = mod.CaddyModule().ID.Name()
	}
	return name
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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.

func GetModules(scope string) []ModuleInfo {
	modulesMu.RLock()
	defer modulesMu.RUnlock()

	scopeParts := strings.Split(scope, ".")

	// handle the special case of an empty scope, which
	// should match only the top-level modules
	if scope == "" {
		scopeParts = []string{}
	}

	var mods []ModuleInfo
iterateModules:
	for id, m := range modules {
		modParts := strings.Split(id, ".")

		// match only the next level of nesting
		if len(modParts) != len(scopeParts)+1 {
			continue
		}

		// specified parts must be exact matches
		for i := range scopeParts {
			if modParts[i] != scopeParts[i] {
				continue iterateModules
			}
		}

		mods = append(mods, m)
	}

	// make return value deterministic
	sort.Slice(mods, func(i, j int) bool {
		return mods[i].ID < mods[j].ID
	})

	return mods
}

Cognitive complexity: 14, Cyclomatic complexity: 6

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".

func HomeDir() string {
	home := homeDirUnsafe()
	if home == "" && runtime.GOOS == "android" {
		home = "/sdcard"
	}
	if home == "" {
		home = "."
	}
	return home
}

Cognitive complexity: 4, Cyclomatic complexity: 4

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.

func InstanceID() (uuid.UUID, error) {
	appDataDir := AppDataDir()
	uuidFilePath := filepath.Join(appDataDir, "instance.uuid")
	uuidFileBytes, err := os.ReadFile(uuidFilePath)
	if errors.Is(err, fs.ErrNotExist) {
		uuid, err := uuid.NewRandom()
		if err != nil {
			return uuid, err
		}
		err = os.MkdirAll(appDataDir, 0o700)
		if err != nil {
			return uuid, err
		}
		err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0o600)
		return uuid, err
	} else if err != nil {
		return [16]byte{}, err
	}
	return uuid.ParseBytes(uuidFileBytes)
}

Cognitive complexity: 9, Cyclomatic complexity: 5

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

func IsWriterStandardStream

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

func IsWriterStandardStream(wo WriterOpener) bool {
	switch wo.(type) {
	case StdoutWriter, StderrWriter,
		*StdoutWriter, *StderrWriter:
		return true
	}
	return false
}

Cognitive complexity: 3, Cyclomatic complexity: 3

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.

func JoinNetworkAddress(network, host, port string) string {
	var a string
	if network != "" {
		a = network + "/"
	}
	if (host != "" && port == "") || IsUnixNetwork(network) || IsFdNetwork(network) {
		a += host
	} else if port != "" {
		a += net.JoinHostPort(host, port)
	}
	return a
}

Cognitive complexity: 6, Cyclomatic complexity: 7

Uses: net.JoinHostPort.

func ListenerUsage

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

func ListenerUsage(network, addr string) int {
	count, _ := listenerPool.References(listenerKey(network, addr))
	return count
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func Load

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

func Load(cfgJSON []byte, forceReload bool) error {
	if err := notify.Reloading(); err != nil {
		Log().Error("unable to notify service manager of reloading state", zap.Error(err))
	}

	// after reload, notify system of success or, if
	// failure, update with status (error message)
	var err error
	defer func() {
		if err != nil {
			if notifyErr := notify.Error(err, 0); notifyErr != nil {
				Log().Error("unable to notify to service manager of reload error",
					zap.Error(notifyErr),
					zap.String("reload_err", err.Error()))
			}
			return
		}
		if err := notify.Ready(); err != nil {
			Log().Error("unable to notify to service manager of ready state", zap.Error(err))
		}
	}()

	err = changeConfig(http.MethodPost, "/"+rawConfigKey, cfgJSON, "", forceReload)
	if errors.Is(err, errSameConfig) {
		err = nil	// not really an error
	}

	return err
}

Cognitive complexity: 11, Cyclomatic complexity: 6

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

func Log

Log returns the current default logger.

func Log() *zap.Logger {
	defaultLoggerMu.RLock()
	defer defaultLoggerMu.RUnlock()
	return defaultLogger.logger
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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.

func NewContext(ctx Context) (Context, context.CancelFunc) {
	newCtx := Context{moduleInstances: make(map[string][]Module), cfg: ctx.cfg, metricsRegistry: prometheus.NewPedanticRegistry()}
	c, cancel := context.WithCancel(ctx.Context)
	wrappedCancel := func() {
		cancel()

		for _, f := range ctx.cleanupFuncs {
			f()
		}

		for modName, modInstances := range newCtx.moduleInstances {
			for _, inst := range modInstances {
				if cu, ok := inst.(CleanerUpper); ok {
					err := cu.Cleanup()
					if err != nil {
						log.Printf("[ERROR] %s (%p): cleanup: %v", modName, inst, err)
					}
				}
			}
		}
	}
	newCtx.Context = c
	newCtx.initMetrics()
	return newCtx, wrappedCancel
}

Cognitive complexity: 15, Cyclomatic complexity: 6

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

func NewEmptyReplacer

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

func NewEmptyReplacer() *Replacer {
	rep := &Replacer{
		static:		make(map[string]any),
		mapMutex:	&sync.RWMutex{},
	}
	rep.providers = []replacementProvider{
		ReplacerFunc(rep.fromStatic),
	}
	return rep
}

Cognitive complexity: 3, Cyclomatic complexity: 1

Uses: sync.RWMutex.

func NewReplacer

NewReplacer returns a new Replacer.

func NewReplacer() *Replacer {
	rep := &Replacer{
		static:		make(map[string]any),
		mapMutex:	&sync.RWMutex{},
	}
	rep.providers = []replacementProvider{
		globalDefaultReplacementProvider{},
		fileReplacementProvider{},
		ReplacerFunc(rep.fromStatic),
	}
	return rep
}

Cognitive complexity: 5, Cyclomatic complexity: 1

Uses: sync.RWMutex.

func NewUsagePool

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

func NewUsagePool() *UsagePool {
	return &UsagePool{
		pool: make(map[any]*usagePoolVal),
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

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 OnExit(f func(context.Context)) {
	exitFuncsMu.Lock()
	exitFuncs = append(exitFuncs, f)
	exitFuncsMu.Unlock()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func PIDFile

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

func PIDFile(filename string) error {
	pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
	err := os.WriteFile(filename, pid, 0o600)
	if err != nil {
		return err
	}
	pidfile = filename
	return nil
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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.

func ParseDuration(s string) (time.Duration, error) {
	if len(s) > 1024 {
		return 0, fmt.Errorf("parsing duration: input string too long")
	}
	var inNumber bool
	var numStart int
	for i := 0; i < len(s); i++ {
		ch := s[i]
		if ch == 'd' {
			daysStr := s[numStart:i]
			days, err := strconv.ParseFloat(daysStr, 64)
			if err != nil {
				return 0, err
			}
			hours := days * 24.0
			hoursStr := strconv.FormatFloat(hours, 'f', -1, 64)
			s = s[:numStart] + hoursStr + "h" + s[i+1:]
			i--
			continue
		}
		if !inNumber {
			numStart = i
		}
		inNumber = (ch >= '0' && ch <= '9') || ch == '.' || ch == '-' || ch == '+'
	}
	return time.ParseDuration(s)
}

Cognitive complexity: 10, Cyclomatic complexity: 10

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 ParseNetworkAddress(addr string) (NetworkAddress, error) {
	return ParseNetworkAddressWithDefaults(addr, "tcp", 0)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func ParseNetworkAddressWithDefaults

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

func ParseNetworkAddressWithDefaults(addr, defaultNetwork string, defaultPort uint) (NetworkAddress, error) {
	var host, port string
	network, host, port, err := SplitNetworkAddress(addr)
	if err != nil {
		return NetworkAddress{}, err
	}
	if network == "" {
		network = defaultNetwork
	}
	if IsUnixNetwork(network) {
		_, _, err := internal.SplitUnixSocketPermissionsBits(host)
		return NetworkAddress{
			Network:	network,
			Host:		host,
		}, err
	}
	if IsFdNetwork(network) {
		return NetworkAddress{
			Network:	network,
			Host:		host,
		}, nil
	}
	var start, end uint64
	if port == "" {
		start = uint64(defaultPort)
		end = uint64(defaultPort)
	} else {
		before, after, found := strings.Cut(port, "-")
		if !found {
			after = before
		}
		start, err = strconv.ParseUint(before, 10, 16)
		if err != nil {
			return NetworkAddress{}, fmt.Errorf("invalid start port: %v", err)
		}
		end, err = strconv.ParseUint(after, 10, 16)
		if err != nil {
			return NetworkAddress{}, fmt.Errorf("invalid end port: %v", err)
		}
		if end < start {
			return NetworkAddress{}, fmt.Errorf("end port must not be less than start port")
		}
		if (end - start) > maxPortSpan {
			return NetworkAddress{}, fmt.Errorf("port range exceeds %d ports", maxPortSpan)
		}
	}
	return NetworkAddress{
		Network:	network,
		Host:		host,
		StartPort:	uint(start),
		EndPort:	uint(end),
	}, nil
}

Cognitive complexity: 30, Cyclomatic complexity: 11

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 ..."

func ParseStructTag(tag string) (map[string]string, error) {
	results := make(map[string]string)
	pairs := strings.Split(tag, " ")
	for i, pair := range pairs {
		if pair == "" {
			continue
		}
		before, after, isCut := strings.Cut(pair, "=")
		if !isCut {
			return nil, fmt.Errorf("missing key in '%s' (pair %d)", pair, i)
		}
		results[before] = after
	}
	return results, nil
}

Cognitive complexity: 7, Cyclomatic complexity: 4

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 ProvisionContext(newCfg *Config) (Context, error) {
	return provisionContext(newCfg, false)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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.

func RegisterModule(instance Module) {
	mod := instance.CaddyModule()

	if mod.ID == "" {
		panic("module ID missing")
	}
	if mod.ID == "caddy" || mod.ID == "admin" {
		panic(fmt.Sprintf("module ID '%s' is reserved", mod.ID))
	}
	if mod.New == nil {
		panic("missing ModuleInfo.New")
	}
	if val := mod.New(); val == nil {
		panic("ModuleInfo.New must return a non-nil module instance")
	}

	modulesMu.Lock()
	defer modulesMu.Unlock()

	if _, ok := modules[string(mod.ID)]; ok {
		panic(fmt.Sprintf("module already registered: %s", mod.ID))
	}
	modules[string(mod.ID)] = mod
}

Cognitive complexity: 10, Cyclomatic complexity: 7

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.

func RegisterNetwork(network string, getListener ListenerFunc) {
	network = strings.TrimSpace(strings.ToLower(network))

	if network == "tcp" || network == "tcp4" || network == "tcp6" ||
		network == "udp" || network == "udp4" || network == "udp6" ||
		network == "unix" || network == "unixpacket" || network == "unixgram" ||
		strings.HasPrefix("ip:", network) || strings.HasPrefix("ip4:", network) || strings.HasPrefix("ip6:", network) ||
		network == "fd" || network == "fdgram" {
		panic("network type " + network + " is reserved")
	}

	if _, ok := networkTypes[strings.ToLower(network)]; ok {
		panic("network type " + network + " is already registered")
	}

	networkTypes[network] = getListener
}

Cognitive complexity: 4, Cyclomatic complexity: 16

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.)

func RemoveMetaFields(rawJSON []byte) []byte {
	return idRegexp.ReplaceAllFunc(rawJSON, func(in []byte) []byte {
		// matches with a comma on both sides (when "@id" property is
		// not the first or last in the object) need to keep exactly
		// one comma for correct JSON syntax
		comma := []byte{','}
		if bytes.HasPrefix(in, comma) && bytes.HasSuffix(in, comma) {
			return comma
		}
		return []byte{}
	})
}

Cognitive complexity: 5, Cyclomatic complexity: 3

Uses: bytes.HasPrefix, bytes.HasSuffix.

func Run

Run runs the given config, replacing any existing config.

func Run(cfg *Config) error {
	cfgJSON, err := json.Marshal(cfg)
	if err != nil {
		return err
	}
	return Load(cfgJSON, true)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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.

func SplitNetworkAddress(a string) (network, host, port string, err error) {
	beforeSlash, afterSlash, slashFound := strings.Cut(a, "/")
	if slashFound {
		network = strings.ToLower(strings.TrimSpace(beforeSlash))
		a = afterSlash
		if IsUnixNetwork(network) || IsFdNetwork(network) {
			host = a
			return
		}
	}

	host, port, err = net.SplitHostPort(a)
	firstErr := err

	if err != nil {
		// in general, if there was an error, it was likely "missing port",
		// so try removing square brackets around an IPv6 host, adding a bogus
		// port to take advantage of standard library's robust parser, then
		// strip the artificial port.
		host, _, err = net.SplitHostPort(net.JoinHostPort(strings.Trim(a, "[]"), "0"))
		port = ""
	}

	if err != nil {
		err = errors.Join(firstErr, err)
	}

	return
}

Cognitive complexity: 8, Cyclomatic complexity: 6

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 Stop() error {
	currentCtxMu.RLock()
	ctx := currentCtx
	currentCtxMu.RUnlock()

	rawCfgMu.Lock()
	unsyncedStop(ctx)

	currentCtxMu.Lock()
	currentCtx = Context{}
	currentCtxMu.Unlock()

	rawCfgJSON = nil
	rawCfgIndex = nil
	rawCfg[rawConfigKey] = nil
	rawCfgMu.Unlock()

	return nil
}

Cognitive complexity: 1, Cyclomatic complexity: 1

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.

func StrictUnmarshalJSON(data []byte, v any) error {
	dec := json.NewDecoder(bytes.NewReader(data))
	dec.DisallowUnknownFields()
	return dec.Decode(v)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: bytes.NewReader, json.NewDecoder.

func ToString

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

func ToString(val any) string {
	switch v := val.(type) {
	case nil:
		return ""
	case string:
		return v
	case fmt.Stringer:
		return v.String()
	case error:
		return v.Error()
	case byte:
		return string(v)
	case []byte:
		return string(v)
	case []rune:
		return string(v)
	case int:
		return strconv.Itoa(v)
	case int32:
		return strconv.Itoa(int(v))
	case int64:
		return strconv.Itoa(int(v))
	case uint:
		return strconv.FormatUint(uint64(v), 10)
	case uint32:
		return strconv.FormatUint(uint64(v), 10)
	case uint64:
		return strconv.FormatUint(v, 10)
	case float32:
		return strconv.FormatFloat(float64(v), 'f', -1, 32)
	case float64:
		return strconv.FormatFloat(v, 'f', -1, 64)
	case bool:
		if v {
			return "true"
		}
		return "false"
	default:
		return fmt.Sprintf("%+v", v)
	}
}

Cognitive complexity: 20, Cyclomatic complexity: 19

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 TrapSignals() {
	trapSignalsCrossPlatform()
	trapSignalsPosix()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func Validate

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

func Validate(cfg *Config) error {
	_, err := run(cfg, false)
	if err == nil {
		cfg.cancelFunc()	// call Cleanup on all modules
	}
	return err
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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.

func Version() (simple, full string) {
	// the currently-recommended way to build Caddy involves
	// building it as a dependency so we can extract version
	// information from go.mod tooling; once the upstream
	// Go issues are fixed, we should just be able to use
	// bi.Main... hopefully.
	var module *debug.Module
	bi, ok := debug.ReadBuildInfo()
	if !ok {
		if CustomVersion != "" {
			full = CustomVersion
			simple = CustomVersion
			return
		}
		full = "unknown"
		simple = "unknown"
		return
	}
	// find the Caddy module in the dependency list
	for _, dep := range bi.Deps {
		if dep.Path == ImportPath {
			module = dep
			break
		}
	}
	if module != nil {
		simple, full = module.Version, module.Version
		if module.Sum != "" {
			full += " " + module.Sum
		}
		if module.Replace != nil {
			full += " => " + module.Replace.Path
			if module.Replace.Version != "" {
				simple = module.Replace.Version + "_custom"
				full += "@" + module.Replace.Version
			}
			if module.Replace.Sum != "" {
				full += " " + module.Replace.Sum
			}
		}
	}

	if full == "" {
		var vcsRevision string
		var vcsTime time.Time
		var vcsModified bool
		for _, setting := range bi.Settings {
			switch setting.Key {
			case "vcs.revision":
				vcsRevision = setting.Value
			case "vcs.time":
				vcsTime, _ = time.Parse(time.RFC3339, setting.Value)
			case "vcs.modified":
				vcsModified, _ = strconv.ParseBool(setting.Value)
			}
		}

		if vcsRevision != "" {
			var modified string
			if vcsModified {
				modified = "+modified"
			}
			full = fmt.Sprintf("%s%s (%s)", vcsRevision, modified, vcsTime.Format(time.RFC822))
			simple = vcsRevision

			// use short checksum for simple, if hex-only
			if _, err := hex.DecodeString(simple); err == nil {
				simple = simple[:8]
			}

			// append date to simple since it can be convenient
			// to know the commit date as part of the version
			if !vcsTime.IsZero() {
				simple += "-" + vcsTime.Format("20060102")
			}
		}
	}

	if full == "" {
		if CustomVersion != "" {
			full = CustomVersion
		} else {
			full = "unknown"
		}
	} else if CustomVersion != "" {
		full = CustomVersion + " " + full
	}

	if simple == "" || simple == "(devel)" {
		if CustomVersion != "" {
			simple = CustomVersion
		} else {
			simple = "unknown"
		}
	}

	return
}

Cognitive complexity: 51, Cyclomatic complexity: 26

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.

func (ctx *Context) Filesystems() FileSystems {
	// if no config is loaded, we use a default filesystemmap, which includes the osfs
	if ctx.cfg == nil {
		return &filesystems.FilesystemMap{}
	}
	return ctx.cfg.filesystems
}

Cognitive complexity: 3, Cyclomatic complexity: 2

Uses: filesystems.FilesystemMap.

func (*Context) GetMetricsRegistry

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

func (ctx *Context) GetMetricsRegistry() *prometheus.Registry {
	return ctx.metricsRegistry
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Context) OnCancel

OnCancel executes f when ctx is canceled.

func (ctx *Context) OnCancel(f func()) {
	ctx.cleanupFuncs = append(ctx.cleanupFuncs, f)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Context) WithValue

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

func (ctx *Context) WithValue(key, value any) Context {
	return Context{
		Context:		context.WithValue(ctx.Context, key, value),
		moduleInstances:	ctx.moduleInstances,
		cfg:			ctx.cfg,
		ancestry:		ctx.ancestry,
		cleanupFuncs:		ctx.cleanupFuncs,
		exitFuncs:		ctx.exitFuncs,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

Uses: context.WithValue.

func (*Duration) UnmarshalJSON

UnmarshalJSON satisfies json.Unmarshaler.

func (d *Duration) UnmarshalJSON(b []byte) error {
	if len(b) == 0 {
		return io.EOF
	}
	var dur time.Duration
	var err error
	if b[0] == byte('"') && b[len(b)-1] == byte('"') {
		dur, err = ParseDuration(strings.Trim(string(b), `"`))
	} else {
		err = json.Unmarshal(b, &dur)
	}
	*d = Duration(dur)
	return err
}

Cognitive complexity: 6, Cyclomatic complexity: 3

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

func (*Replacer) Delete

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

func (r *Replacer) Delete(variable string) {
	r.mapMutex.Lock()
	delete(r.static, variable)
	r.mapMutex.Unlock()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Replacer) Get

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

func (r *Replacer) Get(variable string) (any, bool) {
	for _, mapFunc := range r.providers {
		if val, ok := mapFunc.replace(variable); ok {
			return val, true
		}
	}
	return nil, false
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*Replacer) GetString

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

func (r *Replacer) GetString(variable string) (string, bool) {
	s, found := r.Get(variable)
	return ToString(s), found
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Replacer) Map

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

func (r *Replacer) Map(mapFunc ReplacerFunc) {
	r.providers = append(r.providers, mapFunc)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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 (r *Replacer) ReplaceAll(input, empty string) string {
	out, _ := r.replace(input, empty, true, false, false, nil)
	return out
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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 (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error) {
	return r.replace(input, "", true, false, false, f)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Replacer) ReplaceKnown

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

func (r *Replacer) ReplaceKnown(input, empty string) string {
	out, _ := r.replace(input, empty, false, false, false, nil)
	return out
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Replacer) ReplaceOrErr

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

func (r *Replacer) ReplaceOrErr(input string, errOnEmpty, errOnUnknown bool) (string, error) {
	return r.replace(input, "", false, errOnEmpty, errOnUnknown, nil)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Replacer) Set

Set sets a custom variable to a static value.

func (r *Replacer) Set(variable string, value any) {
	r.mapMutex.Lock()
	r.static[variable] = value
	r.mapMutex.Unlock()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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 (r *Replacer) WithoutFile() *Replacer {
	rep := &Replacer{static: r.static}
	for _, v := range r.providers {
		if _, ok := v.(fileReplacementProvider); ok {
			continue
		}
		rep.providers = append(rep.providers, v)
	}
	return rep
}

Cognitive complexity: 6, Cyclomatic complexity: 3

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.

func (up *UsagePool) LoadOrNew(key any, construct Constructor) (value any, loaded bool, err error) {
	var upv *usagePoolVal
	up.Lock()
	upv, loaded = up.pool[key]
	if loaded {
		atomic.AddInt32(&upv.refs, 1)
		up.Unlock()
		upv.RLock()
		value = upv.value
		err = upv.err
		upv.RUnlock()
	} else {
		upv = &usagePoolVal{refs: 1}
		upv.Lock()
		up.pool[key] = upv
		up.Unlock()
		value, err = construct()
		if err == nil {
			upv.value = value
		} else {
			upv.err = err
			up.Lock()
			// this *should* be safe, I think, because we have a
			// write lock on upv, but we might also need to ensure
			// that upv.err is nil before doing this, since we
			// released the write lock on up during construct...
			// but then again it's also after midnight...
			delete(up.pool, key)
			up.Unlock()
		}
		upv.Unlock()
	}
	return
}

Cognitive complexity: 9, Cyclomatic complexity: 3

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.

func (up *UsagePool) LoadOrStore(key, val any) (value any, loaded bool) {
	var upv *usagePoolVal
	up.Lock()
	upv, loaded = up.pool[key]
	if loaded {
		atomic.AddInt32(&upv.refs, 1)
		up.Unlock()
		upv.Lock()
		if upv.err == nil {
			value = upv.value
		} else {
			upv.value = val
			upv.err = nil
		}
		upv.Unlock()
	} else {
		upv = &usagePoolVal{refs: 1, value: val}
		up.pool[key] = upv
		up.Unlock()
		value = val
	}
	return
}

Cognitive complexity: 9, Cyclomatic complexity: 3

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 (up *UsagePool) Range(f func(key, value any) bool) {
	up.RLock()
	defer up.RUnlock()
	for key, upv := range up.pool {
		upv.RLock()
		if upv.err != nil {
			upv.RUnlock()
			continue
		}
		val := upv.value
		upv.RUnlock()
		if !f(key, val) {
			break
		}
	}
}

Cognitive complexity: 7, Cyclomatic complexity: 4

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.

func (up *UsagePool) References(key any) (int, bool) {
	up.RLock()
	upv, loaded := up.pool[key]
	up.RUnlock()
	if loaded {
		// I wonder if it'd be safer to read this value during
		// our lock on the UsagePool... guess we'll see...
		refs := atomic.LoadInt32(&upv.refs)
		return int(refs), true
	}
	return 0, false
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: atomic.LoadInt32.

func (*delegator) WriteHeader

func (d *delegator) WriteHeader(code int) {
	d.status = code
	d.ResponseWriter.WriteHeader(code)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

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.

func (fcql *fakeCloseQuicListener) Accept(_ context.Context) (quic.EarlyConnection, error) {
	conn, err := fcql.sharedQuicListener.Accept(fcql.context)
	if err == nil {
		return conn, nil
	}

	// if the listener is "closed", return a fake closed error instead
	if atomic.LoadInt32(&fcql.closed) == 1 && errors.Is(err, context.Canceled) {
		return nil, fakeClosedErr(fcql)
	}
	return nil, err
}

Cognitive complexity: 4, Cyclomatic complexity: 4

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

func (*filteringCore) Check

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

func (fc *filteringCore) Check(e zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
	if fc.cl.loggerAllowed(e.LoggerName, false) {
		return fc.Core.Check(e, ce)
	}
	return ce
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*filteringCore) With

With properly wraps With.

func (fc *filteringCore) With(fields []zapcore.Field) zapcore.Core {
	return &filteringCore{
		Core:	fc.Core.With(fields),
		cl:	fc.cl,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*sharedQuicListener) Destruct

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

func (sql *sharedQuicListener) Destruct() error {
	// close EarlyListener first to stop any operations being done to the net.PacketConn
	_ = sql.EarlyListener.Close()
	// then close the net.PacketConn
	return sql.packetConn.Close()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*unixConn) Unwrap

func (uc *unixConn) Unwrap() net.PacketConn {
	return uc.UnixConn
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*unixListener) Close

func (uln *unixListener) Close() error {
	newCount := atomic.AddInt32(uln.count, -1)
	if newCount == 0 {
		file, err := uln.File()
		var name string
		if err == nil {
			name = file.Name()
		}
		defer func() {
			unixSocketsMu.Lock()
			delete(unixSockets, uln.mapKey)
			unixSocketsMu.Unlock()
			if err == nil {
				_ = syscall.Unlink(name)
			}
		}()
	}
	return uln.UnixListener.Close()
}

Cognitive complexity: 7, Cyclomatic complexity: 4

Uses: atomic.AddInt32, syscall.Unlink.

func (APIError) Error

func (e APIError) Error() string {
	if e.Err != nil {
		return e.Err.Error()
	}
	return e.Message
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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.

func (ctx Context) App(name string) (any, error) {
	if app, ok := ctx.cfg.apps[name]; ok {
		return app, nil
	}
	appRaw := ctx.cfg.AppsRaw[name]
	modVal, err := ctx.LoadModuleByID(name, appRaw)
	if err != nil {
		return nil, fmt.Errorf("loading %s app module: %v", name, err)
	}
	if appRaw != nil {
		ctx.cfg.AppsRaw[name] = nil	// allow GC to deallocate
	}
	ctx.cfg.apps[name] = modVal.(App)
	return modVal, nil
}

Cognitive complexity: 6, Cyclomatic complexity: 4

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.

func (ctx Context) AppIfConfigured(name string) (any, error) {
	if ctx.cfg == nil {
		return nil, fmt.Errorf("app module %s: %w", name, ErrNotConfigured)
	}
	if app, ok := ctx.cfg.apps[name]; ok {
		return app, nil
	}
	appRaw := ctx.cfg.AppsRaw[name]
	if appRaw == nil {
		return nil, fmt.Errorf("app module %s: %w", name, ErrNotConfigured)
	}
	return ctx.App(name)
}

Cognitive complexity: 6, Cyclomatic complexity: 4

Uses: fmt.Errorf.

func (Context) IdentityCredentials

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

func (ctx Context) IdentityCredentials(logger *zap.Logger) ([]tls.Certificate, error) {
	if ctx.cfg == nil || ctx.cfg.Admin == nil || ctx.cfg.Admin.Identity == nil {
		return nil, fmt.Errorf("no server identity configured")
	}
	ident := ctx.cfg.Admin.Identity
	if len(ident.Identifiers) == 0 {
		return nil, fmt.Errorf("no identifiers configured")
	}
	if logger == nil {
		logger = Log()
	}
	magic := ident.certmagicConfig(logger, false)
	return magic.ClientCredentials(ctx, ident.Identifiers)
}

Cognitive complexity: 6, Cyclomatic complexity: 6

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.

func (ctx Context) LoadModule(structPointer any, fieldName string) (any, error) {
	val := reflect.ValueOf(structPointer).Elem().FieldByName(fieldName)
	typ := val.Type()

	field, ok := reflect.TypeOf(structPointer).Elem().FieldByName(fieldName)
	if !ok {
		panic(fmt.Sprintf("field %s does not exist in %#v", fieldName, structPointer))
	}

	opts, err := ParseStructTag(field.Tag.Get("caddy"))
	if err != nil {
		panic(fmt.Sprintf("malformed tag on field %s: %v", fieldName, err))
	}

	moduleNamespace, ok := opts["namespace"]
	if !ok {
		panic(fmt.Sprintf("missing 'namespace' key in struct tag on field %s", fieldName))
	}
	inlineModuleKey := opts["inline_key"]

	var result any

	switch val.Kind() {
	case reflect.Slice:
		if isJSONRawMessage(typ) {
			// val is `json.RawMessage` ([]uint8 under the hood)

			if inlineModuleKey == "" {
				panic("unable to determine module name without inline_key when type is not a ModuleMap")
			}
			val, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, val.Interface().(json.RawMessage))
			if err != nil {
				return nil, err
			}
			result = val
		} else if isJSONRawMessage(typ.Elem()) {
			// val is `[]json.RawMessage`

			if inlineModuleKey == "" {
				panic("unable to determine module name without inline_key because type is not a ModuleMap")
			}
			var all []any
			for i := 0; i < val.Len(); i++ {
				val, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, val.Index(i).Interface().(json.RawMessage))
				if err != nil {
					return nil, fmt.Errorf("position %d: %v", i, err)
				}
				all = append(all, val)
			}
			result = all
		} else if typ.Elem().Kind() == reflect.Slice && isJSONRawMessage(typ.Elem().Elem()) {
			// val is `[][]json.RawMessage`

			if inlineModuleKey == "" {
				panic("unable to determine module name without inline_key because type is not a ModuleMap")
			}
			var all [][]any
			for i := 0; i < val.Len(); i++ {
				innerVal := val.Index(i)
				var allInner []any
				for j := 0; j < innerVal.Len(); j++ {
					innerInnerVal, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, innerVal.Index(j).Interface().(json.RawMessage))
					if err != nil {
						return nil, fmt.Errorf("position %d: %v", j, err)
					}
					allInner = append(allInner, innerInnerVal)
				}
				all = append(all, allInner)
			}
			result = all
		} else if isModuleMapType(typ.Elem()) {
			// val is `[]map[string]json.RawMessage`

			var all []map[string]any
			for i := 0; i < val.Len(); i++ {
				thisSet, err := ctx.loadModulesFromSomeMap(moduleNamespace, inlineModuleKey, val.Index(i))
				if err != nil {
					return nil, err
				}
				all = append(all, thisSet)
			}
			result = all
		}

	case reflect.Map:
		// val is a ModuleMap or some other kind of map
		result, err = ctx.loadModulesFromSomeMap(moduleNamespace, inlineModuleKey, val)
		if err != nil {
			return nil, err
		}

	default:
		return nil, fmt.Errorf("unrecognized type for module: %s", typ)
	}

	// we're done with the raw bytes; allow GC to deallocate
	val.Set(reflect.Zero(typ))

	return result, nil
}

Cognitive complexity: 42, Cyclomatic complexity: 24

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.

func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (any, error) {
	modulesMu.RLock()
	modInfo, ok := modules[id]
	modulesMu.RUnlock()
	if !ok {
		return nil, fmt.Errorf("unknown module: %s", id)
	}

	if modInfo.New == nil {
		return nil, fmt.Errorf("module '%s' has no constructor", modInfo.ID)
	}

	val := modInfo.New()

	// value must be a pointer for unmarshaling into concrete type, even if
	// the module's concrete type is a slice or map; New() *should* return
	// a pointer, otherwise unmarshaling errors or panics will occur
	if rv := reflect.ValueOf(val); rv.Kind() != reflect.Ptr {
		log.Printf("[WARNING] ModuleInfo.New() for module '%s' did not return a pointer,"+
			" so we are using reflection to make a pointer instead; please fix this by"+
			" using new(Type) or &Type notation in your module's New() function.", id)
		val = reflect.New(rv.Type()).Elem().Addr().Interface().(Module)
	}

	// fill in its config only if there is a config to fill in
	if len(rawMsg) > 0 {
		err := StrictUnmarshalJSON(rawMsg, &val)
		if err != nil {
			return nil, fmt.Errorf("decoding module config: %s: %v", modInfo, err)
		}
	}

	if val == nil {
		// returned module values are almost always type-asserted
		// before being used, so a nil value would panic; and there
		// is no good reason to explicitly declare null modules in
		// a config; it might be because the user is trying to achieve
		// a result the developer isn't expecting, which is a smell
		return nil, fmt.Errorf("module value cannot be null")
	}

	ctx.ancestry = append(ctx.ancestry, val)

	if prov, ok := val.(Provisioner); ok {
		err := prov.Provision(ctx)
		if err != nil {
			// incomplete provisioning could have left state
			// dangling, so make sure it gets cleaned up
			if cleanerUpper, ok := val.(CleanerUpper); ok {
				err2 := cleanerUpper.Cleanup()
				if err2 != nil {
					err = fmt.Errorf("%v; additionally, cleanup: %v", err, err2)
				}
			}
			return nil, fmt.Errorf("provision %s: %v", modInfo, err)
		}
	}

	if validator, ok := val.(Validator); ok {
		err := validator.Validate()
		if err != nil {
			// since the module was already provisioned, make sure we clean up
			if cleanerUpper, ok := val.(CleanerUpper); ok {
				err2 := cleanerUpper.Cleanup()
				if err2 != nil {
					err = fmt.Errorf("%v; additionally, cleanup: %v", err, err2)
				}
			}
			return nil, fmt.Errorf("%s: invalid configuration: %v", modInfo, err)
		}
	}

	ctx.moduleInstances[id] = append(ctx.moduleInstances[id], val)

	return val, nil
}

Cognitive complexity: 28, Cyclomatic complexity: 15

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.

func (ctx Context) Logger(module ...Module) *zap.Logger {
	if len(module) > 1 {
		panic("more than 1 module passed in")
	}
	if ctx.cfg == nil {
		// often the case in tests; just use a dev logger
		l, err := zap.NewDevelopment()
		if err != nil {
			panic("config missing, unable to create dev logger: " + err.Error())
		}
		return l
	}
	mod := ctx.Module()
	if len(module) > 0 {
		mod = module[0]
	}
	if mod == nil {
		return Log()
	}
	return ctx.cfg.Logging.Logger(mod)
}

Cognitive complexity: 10, Cyclomatic complexity: 6

Uses: zap.NewDevelopment.

func (Context) Module

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

func (ctx Context) Module() Module {
	if len(ctx.ancestry) == 0 {
		return nil
	}
	return ctx.ancestry[len(ctx.ancestry)-1]
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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 (ctx Context) Modules() []Module {
	mods := make([]Module, len(ctx.ancestry))
	copy(mods, ctx.ancestry)
	return mods
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (Context) Slogger

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

func (ctx Context) Slogger() *slog.Logger {
	if ctx.cfg == nil {
		// often the case in tests; just use a dev logger
		l, err := zap.NewDevelopment()
		if err != nil {
			panic("config missing, unable to create dev logger: " + err.Error())
		}
		return slog.New(zapslog.NewHandler(l.Core(), nil))
	}
	mod := ctx.Module()
	if mod == nil {
		return slog.New(zapslog.NewHandler(Log().Core(), nil))
	}
	return slog.New(zapslog.NewHandler(ctx.cfg.Logging.Logger(mod).Core(),
		zapslog.WithName(string(mod.CaddyModule().ID)),
	))
}

Cognitive complexity: 6, Cyclomatic complexity: 4

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

func (Context) Storage

Storage returns the configured Caddy storage implementation.

func (ctx Context) Storage() certmagic.Storage {
	return ctx.cfg.storage
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (ModuleID) Name

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

func (id ModuleID) Name() string {
	if id == "" {
		return ""
	}
	parts := strings.Split(string(id), ".")
	return parts[len(parts)-1]
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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.

func (id ModuleID) Namespace() string {
	lastDot := strings.LastIndex(string(id), ".")
	if lastDot < 0 {
		return ""
	}
	return string(id)[:lastDot]
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: strings.LastIndex.

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 (na NetworkAddress) At(portOffset uint) NetworkAddress {
	na2 := na
	na2.StartPort, na2.EndPort = na.StartPort+portOffset, na.StartPort+portOffset
	return na2
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (NetworkAddress) Expand

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

func (na NetworkAddress) Expand() []NetworkAddress {
	size := na.PortRangeSize()
	addrs := make([]NetworkAddress, size)
	for portOffset := uint(0); portOffset < size; portOffset++ {
		addrs[portOffset] = na.At(portOffset)
	}
	return addrs
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (NetworkAddress) IsFdNetwork

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

func (na NetworkAddress) IsFdNetwork() bool {
	return IsFdNetwork(na.Network)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (NetworkAddress) IsUnixNetwork

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

func (na NetworkAddress) IsUnixNetwork() bool {
	return IsUnixNetwork(na.Network)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (NetworkAddress) JoinHostPort

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

func (na NetworkAddress) JoinHostPort(offset uint) string {
	if na.IsUnixNetwork() || na.IsFdNetwork() {
		return na.Host
	}
	return net.JoinHostPort(na.Host, strconv.FormatUint(uint64(na.StartPort+offset), 10))
}

Cognitive complexity: 2, Cyclomatic complexity: 3

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 (na NetworkAddress) Listen(ctx context.Context, portOffset uint, config net.ListenConfig) (any, error) {
	if na.IsUnixNetwork() {
		unixSocketsMu.Lock()
		defer unixSocketsMu.Unlock()
	}

	// check to see if plugin provides listener
	if ln, err := getListenerFromPlugin(ctx, na.Network, na.Host, na.port(), portOffset, config); ln != nil || err != nil {
		return ln, err
	}

	// create (or reuse) the listener ourselves
	return na.listen(ctx, portOffset, config)
}

Cognitive complexity: 4, Cyclomatic complexity: 4

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.

func (na NetworkAddress) ListenAll(ctx context.Context, config net.ListenConfig) ([]any, error) {
	var listeners []any
	var err error

	// if one of the addresses has a failure, we need to close
	// any that did open a socket to avoid leaking resources
	defer func() {
		if err == nil {
			return
		}
		for _, ln := range listeners {
			if cl, ok := ln.(io.Closer); ok {
				cl.Close()
			}
		}
	}()

	// an address can contain a port range, which represents multiple addresses;
	// some addresses don't use ports at all and have a port range size of 1;
	// whatever the case, iterate each address represented and bind a socket
	for portOffset := uint(0); portOffset < na.PortRangeSize(); portOffset++ {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		default:
		}

		// create (or reuse) the listener ourselves
		var ln any
		ln, err = na.Listen(ctx, portOffset, config)
		if err != nil {
			return nil, err
		}
		listeners = append(listeners, ln)
	}

	return listeners, nil
}

Cognitive complexity: 14, Cyclomatic complexity: 7

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.

func (na NetworkAddress) ListenQUIC(ctx context.Context, portOffset uint, config net.ListenConfig, tlsConf *tls.Config) (http3.QUICEarlyListener, error) {
	lnKey := listenerKey("quic"+na.Network, na.JoinHostPort(portOffset))

	sharedEarlyListener, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) {
		lnAny, err := na.Listen(ctx, portOffset, config)
		if err != nil {
			return nil, err
		}

		ln := lnAny.(net.PacketConn)

		h3ln := ln
		for {
			// retrieve the underlying socket, so quic-go can optimize.
			if unwrapper, ok := h3ln.(interface{ Unwrap() net.PacketConn }); ok {
				h3ln = unwrapper.Unwrap()
			} else {
				break
			}
		}

		sqs := newSharedQUICState(tlsConf)
		// http3.ConfigureTLSConfig only uses this field and tls App sets this field as well
		//nolint:gosec
		quicTlsConfig := &tls.Config{GetConfigForClient: sqs.getConfigForClient}
		// Require clients to verify their source address when we're handling more than 1000 handshakes per second.
		// TODO: make tunable?
		limiter := rate.NewLimiter(1000, 1000)
		tr := &quic.Transport{
			Conn:			h3ln,
			VerifySourceAddress:	func(addr net.Addr) bool { return !limiter.Allow() },
		}
		earlyLn, err := tr.ListenEarly(
			http3.ConfigureTLSConfig(quicTlsConfig),
			&quic.Config{
				Allow0RTT:	true,
				Tracer:		qlog.DefaultConnectionTracer,
			},
		)
		if err != nil {
			return nil, err
		}
		// TODO: figure out when to close the listener and the transport
		// using the original net.PacketConn to close them properly
		return &sharedQuicListener{EarlyListener: earlyLn, packetConn: ln, sqs: sqs, key: lnKey}, nil
	})
	if err != nil {
		return nil, err
	}

	sql := sharedEarlyListener.(*sharedQuicListener)
	// add current tls.Config to sqs, so GetConfigForClient will always return the latest tls.Config in case of context cancellation
	ctx, cancel := sql.sqs.addState(tlsConf)

	return &fakeCloseQuicListener{
		sharedQuicListener:	sql,
		context:		ctx,
		contextCancel:		cancel,
	}, nil
}

Cognitive complexity: 20, Cyclomatic complexity: 6

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 (na NetworkAddress) PortRangeSize() uint {
	if na.EndPort < na.StartPort {
		return 0
	}
	return (na.EndPort - na.StartPort) + 1
}

Cognitive complexity: 2, Cyclomatic complexity: 2

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 (na NetworkAddress) String() string {
	if na.Network == "tcp" && (na.Host != "" || na.port() != "") {
		na.Network = ""	// omit default network value for brevity
	}
	return JoinNetworkAddress(na.Network, na.Host, na.port())
}

Cognitive complexity: 2, Cyclomatic complexity: 4

func (StdoutWriter) CaddyModule

CaddyModule returns the Caddy module information.

func (StdoutWriter) CaddyModule() ModuleInfo {
	return ModuleInfo{
		ID:	"caddy.logging.writers.stdout",
		New:	func() Module { return new(StdoutWriter) },
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 1

func (StdoutWriter) OpenWriter

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

func (StdoutWriter) OpenWriter() (io.WriteCloser, error) {
	return notClosable{os.Stdout}, nil
}

Cognitive complexity: 1, Cyclomatic complexity: 1

Uses: os.Stdout.

func (StdoutWriter) WriterKey

WriterKey returns a unique key representing stdout.

func (StdoutWriter) WriterKey() string	{ return "std:out" }

Cognitive complexity: 0, Cyclomatic complexity: 1

func (adminHandler) ServeHTTP

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

func (h adminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ip, port, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		ip = r.RemoteAddr
		port = ""
	}
	log := Log().Named("admin.api").With(
		zap.String("method", r.Method),
		zap.String("host", r.Host),
		zap.String("uri", r.RequestURI),
		zap.String("remote_ip", ip),
		zap.String("remote_port", port),
		zap.Reflect("headers", r.Header),
	)
	if r.TLS != nil {
		log = log.With(
			zap.Bool("secure", true),
			zap.Int("verified_chains", len(r.TLS.VerifiedChains)),
		)
	}
	if r.RequestURI == "/metrics" {
		log.Debug("received request")
	} else {
		log.Info("received request")
	}
	h.serveHTTP(w, r)
}

Cognitive complexity: 8, Cyclomatic complexity: 4

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

func (loggableURLArray) MarshalLogArray

func (ua loggableURLArray) MarshalLogArray(enc zapcore.ArrayEncoder) error {
	if ua == nil {
		return nil
	}
	for _, u := range ua {
		enc.AppendString(u.String())
	}
	return nil
}

Cognitive complexity: 5, Cyclomatic complexity: 3

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.

changeConfig (method,path string, input []byte, ifMatchHeader string, forceReload bool) error
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.

decodeBase64DERCert (certStr string) (*x509.Certificate, error)
References: base64.StdEncoding, x509.ParseCertificate.

func etagHasher

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

etagHasher () hash.Hash

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.

exitProcess (ctx context.Context, logger *zap.Logger)
References: atomic.StoreInt32, certmagic.CleanUpOwnLocks, notify.Stopping, os.Exit, os.Remove, zap.Error, zap.Int, zap.String.

func exitProcessFromSignal

exitProcessFromSignal exits the process from a system signal.

exitProcessFromSignal (sigName string)
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

fakeClosedErr (l interface{ Addr() net.Addr }) error
References: net.OpError.

func finishSettingUp

finishSettingUp should be run after all apps have successfully started.

finishSettingUp (ctx Context, cfg *Config) error
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.

getListenerFromPlugin (ctx context.Context, network,host,port string, portOffset uint, config net.ListenConfig) (any, error)
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.

getModuleNameInline (moduleNameKey string, raw json.RawMessage) (string, json.RawMessage, error)
References: fmt.Errorf, json.Marshal, json.Unmarshal.

func handleConfig

handleConfig (w http.ResponseWriter, r *http.Request) error
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

handleConfigID (w http.ResponseWriter, r *http.Request) error
References: fmt.Errorf, http.StatusBadRequest, http.StatusNotFound, path.Join, strings.Split.

func handleStop

handleStop (w http.ResponseWriter, r *http.Request) error
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.

homeDirUnsafe () string
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.

indexConfigObjects (ptr any, configPath string, index map[string]string) error
References: fmt.Errorf, fmt.Sprintf, path.Join, strconv.Itoa.

func init

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.

instrumentHandlerCounter (counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc
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.

isJSONRawMessage (typ reflect.Type) bool

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.

isModuleMapType (typ reflect.Type) bool
References: reflect.Map, reflect.String.

func listenReusable

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

listenReusable (ctx context.Context, lnKey string, network,address string, config net.ListenConfig) (any, error)
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

listenerKey (network,addr string) string

func makeEtag

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

makeEtag (path string, hash hash.Hash) string
References: fmt.Sprintf.

func manageIdentity

manageIdentity sets up automated identity management for this server.

manageIdentity (ctx Context, cfg *Config) error
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.

newDefaultProductionLog () (*defaultCustomLog, error)
References: zap.New, zap.RedirectStdLog, zapcore.InfoLevel.

func newDefaultProductionLogEncoder

newDefaultProductionLogEncoder (wo WriterOpener) zapcore.Encoder
References: os.Stderr, term.IsTerminal, time.Time, zap.NewProductionEncoderConfig, zapcore.CapitalColorLevelEncoder, zapcore.NewConsoleEncoder, zapcore.NewJSONEncoder, zapcore.PrimitiveArrayEncoder.

func newDelegator

newDelegator (w http.ResponseWriter) *delegator

func newSharedQUICState

newSharedQUICState creates a new sharedQUICState

newSharedQUICState (tlsConfig *tls.Config) *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.

parseAdminListenAddr (addr string, defaultAddr string) (NetworkAddress, error)
References: fmt.Errorf.

func parseLevel

parseLevel (levelInput string) (zapcore.LevelEnabler, error)
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.

provisionContext (newCfg *Config, replaceAdminServer bool) (Context, error)
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.

readConfig (path string, out io.Writer) error
References: http.MethodGet.

func readFileIntoBuffer

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

readFileIntoBuffer (filename string, size int) ([]byte, error)
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.

replaceLocalAdminServer (cfg *Config, ctx Context) error
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.

replaceRemoteAdminServer (ctx Context, cfg *Config) error
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.

reusePort (network,address string, conn syscall.RawConn) error
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.

reuseUnixSocket (network,addr string) (any, error)
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.

run (newCfg *Config, start bool) (Context, error)
References: fmt.Errorf.

func stopAdminServer

stopAdminServer (srv *http.Server) error
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.

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

func trapSignalsPosix

trapSignalsPosix captures POSIX-only signals.

trapSignalsPosix ()
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).

unsyncedConfigAccess (method,path string, body []byte, out io.Writer) error
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.

unsyncedDecodeAndRun (cfgJSON []byte, allowPersist bool) error
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.

unsyncedStop (ctx Context)
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.

newAdminHandler (addr NetworkAddress, remote bool, _ Context) adminHandler
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.

provisionAdminRouters (ctx Context) error

func buildCore

buildCore ()
References: time.Second, zapcore.AddSync, zapcore.NewCore, zapcore.NewNopCore, zapcore.NewSamplerWithOptions.

func buildOptions

buildOptions () ([]zap.Option, error)
References: fmt.Errorf, zap.AddCaller, zap.AddCallerSkip, zap.AddStacktrace, zap.Option.

func provisionCommon

provisionCommon (ctx Context, logging *Logging) error
References: fmt.Errorf, zapcore.Core, zapcore.Encoder, zapcore.NewTee.

func initMetrics

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.

loggerAllowed (name string, isModule bool) bool
References: strings.HasPrefix.

func matchesModule

matchesModule (moduleID string) bool

func certmagicConfig

certmagicConfig (logger *zap.Logger, makeCache bool) *certmagic.Config
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.

closeLogs () error
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.

openLogs (ctx Context) error
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.

openWriter (opener WriterOpener) (io.WriteCloser, bool, error)
References: io.WriteCloser.

func setupNewDefault

setupNewDefault (ctx Context) error
References: fmt.Errorf, zap.New, zap.String.

func fromStatic

fromStatic provides values from r.static.

fromStatic (key string) (any, bool)

func replace

replace (input,empty string, treatUnknownAsEmpty,errOnEmpty,errOnUnknown bool, f ReplacementFunc) (string, error)
References: fmt.Errorf, strings.Builder, strings.Contains, strings.Index.

func provision

provision (ctx Context, logging *Logging) error
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

addState (tlsConfig *tls.Config) (context.Context, context.CancelFunc)
References: context.Background, context.WithCancel, zap.Int.

func getConfigForClient

getConfigForClient is used as tls.Config's GetConfigForClient field

getConfigForClient (ch *tls.ClientHelloInfo) (*tls.Config, error)

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.

allowedOrigins (addr NetworkAddress) []*url.URL
References: net.JoinHostPort, strings.Contains, url.Parse, url.URL.

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.

loadModuleInline (moduleNameKey,moduleScope string, raw json.RawMessage) (any, error)
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.

loadModuleMap (namespace string, val reflect.Value) (map[string]any, error)
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.

loadModulesFromRegularMap (namespace,inlineModuleKey string, val reflect.Value) (map[string]any, error)
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).

loadModulesFromSomeMap (namespace,inlineModuleKey string, val reflect.Value) (map[string]any, error)
References: fmt.Sprintf.

func isLoopback

isLoopback () bool
References: netip.ParseAddr.

func isWildcardInterface

isWildcardInterface () bool
References: netip.ParseAddr.

func listen

listen (ctx context.Context, portOffset uint, config net.ListenConfig) (any, error)
References: fmt.Errorf, fs.FileMode, os.Chmod, strings.HasPrefix.

func port

port () string
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).

enforceAccessControls (r *http.Request) error
References: crypto.PublicKey, http.StatusForbidden, http.StatusUnauthorized, slices.Contains, strings.HasPrefix.

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.

checkHost (r *http.Request) error
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.

checkOrigin (r *http.Request) (string, error)
References: fmt.Errorf, http.StatusForbidden.

func getOrigin

getOrigin (r *http.Request) (string, *url.URL)
References: url.Parse.

func handleError

handleError (w http.ResponseWriter, r *http.Request, err error)
References: http.StatusInternalServerError, json.NewEncoder, zap.Error, zap.Int.

func originAllowed

originAllowed (origin *url.URL) bool

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).

serveHTTP (w http.ResponseWriter, r *http.Request)
References: fmt.Errorf, http.MethodOptions, strings.Contains.


Tests

Files: 6. Third party imports: 0. Imports from organisation: 0. Tests: 20. Benchmarks: 2.

Vars

var testCfg = []byte(`{
			"apps": {
				"http": {
					"servers": {
						"myserver": {
							"listen": ["tcp/localhost:8080-8084"],
							"read_timeout": "30s"
						},
						"yourserver": {
							"listen": ["127.0.0.1:5000"],
							"read_header_timeout": "15s"
						}
					}
				}
			}
		}
		`)

Types

fooModule

This type doesn't have documentation.

type fooModule struct {
	IntField	int
	StrField	string
}

Test functions

TestETags

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

TestExpand

References: reflect.DeepEqual.

TestGetModules

References: reflect.DeepEqual.

TestJoinHostPort

TestJoinNetworkAddress

TestLoadConcurrent

References: sync.WaitGroup.

TestModuleID

TestParseDuration

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

TestParseNetworkAddress

References: reflect.DeepEqual.

TestParseNetworkAddressWithDefaults

References: reflect.DeepEqual.

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.