Go API Documentation

github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile

No package summary is available.

Package

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

Constants

Vars

Interface guard

defaultDirectiveOrder specifies the default order to apply directives in HTTP routes. This must only consist of directives that are included in Caddy's standard distribution.

e.g. The 'root' directive goes near the start in case rewrites or redirects depend on existence of files, i.e. the file matcher, which must know the root first.

e.g. The 'header' directive goes before 'redir' so that headers can be manipulated before doing redirects.

e.g. The 'respond' directive is near the end because it writes a response and terminates the middleware chain.

directiveOrder specifies the order to apply directives in HTTP routes, after being modified by either the plugins or by the user via the "order" global option.

Types

Address

Address represents a site address. It contains the original input value, and the component parts of an address. The component parts may be updated to the correct values as setup proceeds, but the original value should never be changed.

The Host field must be in a normalized form.

Field name Field type Comment
Original

string

No comment on field.

App

App represents the configuration for a non-standard Caddy app module (e.g. third-party plugin) which was parsed from a global options block.

Field name Field type Comment
Name

string

The JSON key for the app being configured

Value

json.RawMessage

The raw app config as JSON

ComplexShorthandReplacer

This type doesn't have documentation.

Field name Field type Comment
search

*regexp.Regexp

No comment on field.
replace

string

No comment on field.

ConfigValue

ConfigValue represents a value to be added to the final configuration, or a value to be consulted when building the final configuration.

Field name Field type Comment
Class

string

The kind of value this is. As the config is being built, the adapter will look in the "pile" for values belonging to a certain class when it is setting up a certain part of the config. The associated value will be type-asserted and placed accordingly.

Value

any

The value to be used when building the config. Generally its type is associated with the name of the Class.

directive

string

No comment on field.

Helper

Helper is a type which helps setup a value from Caddyfile tokens.

Field name Field type Comment

*caddyfile.Dispenser

No comment on field.
State

map[string]any

State stores intermediate variables during caddyfile adaptation.

options

map[string]any

No comment on field.
warnings

*[]caddyconfig.Warning

No comment on field.
matcherDefs

map[string]caddy.ModuleMap

No comment on field.
parentBlock

caddyfile.ServerBlock

No comment on field.
groupCounter

counter

No comment on field.

Positional

Positional are the supported modes for ordering directives.

Field name Field type Comment
type

string

No comment on field.

ServerType

ServerType can set up a config from an HTTP Caddyfile.

ShorthandReplacer

This type doesn't have documentation.

Field name Field type Comment
complex

[]ComplexShorthandReplacer

No comment on field.
simple

*strings.Replacer

No comment on field.

UnmarshalFunc, UnmarshalHandlerFunc, UnmarshalGlobalFunc

This type doesn't have documentation.

Field name Field type Comment
type

func(h Helper) ([]ConfigValue, error)

No comment on field.
type

func(h Helper) (caddyhttp.MiddlewareHandler, error)

No comment on field.
type

func(d *caddyfile.Dispenser, existingVal any) (any, error)

No comment on field.

acmeCapable

This type doesn't have documentation.

Field name Field type Comment
type

any

No comment on field.

addressWithProtocols

addressWithProtocols associates a listen address with the protocols to serve it with

Field name Field type Comment
address

string

No comment on field.
protocols

[]string

No comment on field.

addressesWithProtocols

addressesWithProtocols associates a list of listen addresses with a list of protocols to serve them with

Field name Field type Comment
addresses

[]string

No comment on field.
protocols

[]string

No comment on field.

counter

This type doesn't have documentation.

Field name Field type Comment
n

*int

No comment on field.

namedCustomLog

This type doesn't have documentation.

Field name Field type Comment
name

string

No comment on field.
hostnames

[]string

No comment on field.
log

*caddy.CustomLog

No comment on field.
noHostname

bool

No comment on field.

sbAddrAssociation

sbAddrAssociation is a mapping from a list of addresses with protocols, and a list of server blocks that are served on those addresses.

Field name Field type Comment
addressesWithProtocols

[]addressWithProtocols

No comment on field.
serverBlocks

[]serverBlock

No comment on field.

serverBlock

serverBlock pairs a Caddyfile server block with a "pile" of config values, keyed by class name, as well as its parsed keys for convenience.

Field name Field type Comment
block

caddyfile.ServerBlock

No comment on field.
pile

map[string][]ConfigValue

No comment on field.
parsedKeys

[]Address

No comment on field.

serverOptions

serverOptions collects server config overrides parsed from Caddyfile global options

Field name Field type Comment
ListenerAddress

string

If set, will only apply these options to servers that contain a listener address that matches exactly. If empty, will apply to all servers that were not already matched by another serverOptions.

Name

string

These will all map 1:1 to the caddyhttp.Server struct

ListenerWrappersRaw

[]json.RawMessage

No comment on field.
ReadTimeout

caddy.Duration

No comment on field.
ReadHeaderTimeout

caddy.Duration

No comment on field.
WriteTimeout

caddy.Duration

No comment on field.
IdleTimeout

caddy.Duration

No comment on field.
KeepAliveInterval

caddy.Duration

No comment on field.
MaxHeaderBytes

int

No comment on field.
EnableFullDuplex

bool

No comment on field.
Protocols

[]string

No comment on field.
StrictSNIHost

*bool

No comment on field.
TrustedProxiesRaw

json.RawMessage

No comment on field.
TrustedProxiesStrict

int

No comment on field.
ClientIPHeaders

[]string

No comment on field.
ShouldLogCredentials

bool

No comment on field.
Metrics

*caddyhttp.Metrics

No comment on field.
Trace

bool

No comment on field.

Functions

func NewShorthandReplacer

Uses: regexp.MustCompile, strings.NewReplacer.

func ParseAddress

ParseAddress parses an address string into a structured format with separate scheme, host, port, and path portions, as well as the original input string.

Uses: fmt.Errorf, net.SplitHostPort, strconv.Atoi, strings.SplitN, strings.TrimSpace.

func ParseSegmentAsSubroute

ParseSegmentAsSubroute parses the segment such that its subdirectives are themselves treated as directives, from which a subroute is built and returned.

func RegisterDirective

RegisterDirective registers a unique directive dir with an associated unmarshaling (setup) function. When directive dir is encountered in a Caddyfile, setupFunc will be called to unmarshal its tokens.

func RegisterDirectiveOrder

RegisterDirectiveOrder registers the default order for a directive from a plugin.

This is useful when a plugin has a well-understood place it should run in the middleware pipeline, and it allows users to avoid having to define the order themselves.

The directive dir may be placed in the position relative to ('before' or 'after') a directive included in Caddy's standard distribution. It cannot be relative to another plugin's directive.

EXPERIMENTAL: This API may change or be removed.

Uses: slices.Contains.

func RegisterGlobalOption

RegisterGlobalOption registers a unique global option opt with an associated unmarshaling (setup) function. When the global option opt is encountered in a Caddyfile, setupFunc will be called to unmarshal its tokens.

func RegisterHandlerDirective

RegisterHandlerDirective is like RegisterDirective, but for directives which specifically output only an HTTP handler. Directives registered with this function will always have an optional matcher token as the first argument.

func WasReplacedPlaceholderShorthand

WasReplacedPlaceholderShorthand checks if a token string was likely a replaced shorthand of the known Caddyfile placeholder replacement outputs. Useful to prevent some user-defined map output destinations from overlapping with one of the predefined shorthands.

Uses: strings.Trim.

func (Address) Normalize

Normalize returns a normalized version of a.

Uses: netip.ParseAddr, strings.TrimSpace.

func (Address) String

String returns a human-readable form of a. It will be a cleaned-up and filled-out URL string.

Uses: caddyhttp.DefaultHTTPPort, caddyhttp.DefaultHTTPSPort, certmagic.HTTPSPort, net.JoinHostPort, strconv.Itoa.

func (Helper) Caddyfiles

Caddyfiles returns the list of config files from which tokens in the current server block were loaded.

Uses: sort.Strings.

func (Helper) ExtractMatcherSet

ExtractMatcherSet is like MatcherToken, except this is a higher-level method that returns the matcher set described by the matcher token, or nil if there is none, and deletes the matcher token from the dispenser and resets it as if this look-ahead never happened. Useful when wrapping a route (one or more handlers) in a user-defined matcher.

func (Helper) GroupRoutes

GroupRoutes adds the routes (caddyhttp.Route type) in vals to the same group, if there is more than one route in vals.

Uses: caddyhttp.Route.

func (Helper) JSON

JSON converts val into JSON. Any errors are added to warnings.

Uses: caddyconfig.JSON.

func (Helper) MatcherToken

MatcherToken assumes the next argument token is (possibly) a matcher, and if so, returns the matcher set along with a true value. If the next token is not a matcher, nil and false is returned. Note that a true value may be returned with a nil matcher set if it is a catch-all.

func (Helper) NewRoute

NewRoute returns config values relevant to creating a new HTTP route.

Uses: caddyconfig.JSONModuleObject, caddyconfig.Warning, caddyhttp.Route, json.RawMessage.

func (Helper) Option

Option gets the option keyed by name.

func (Helper) WithDispenser

WithDispenser returns a new instance based on d. All others Helper fields are copied, so typically maps are shared with this new instance.

func (ServerType) Setup

Setup makes a config from the tokens.

Uses: caddyconfig.JSON, caddyconfig.JSONModuleObject, caddyconfig.Warning, caddyfile.NewDispenser, caddyhttp.App, caddyhttp.Metrics, caddypki.CA, caddypki.PKI, caddytls.TLS, cmp.Or, fmt.Errorf, reflect.DeepEqual, slices.Compact, sort.Strings, strings.HasPrefix, zap.DebugLevel.

func (ShorthandReplacer) ApplyToSegment

ApplyToSegment replaces shorthand placeholder to its full placeholder, understandable by Caddy.

Private functions

func appendSubrouteToRouteList

appendSubrouteToRouteList appends the routes in subroute to the routeList, optionally qualified by matchers.

References: caddyconfig.JSONModuleObject, caddyhttp.Route, json.RawMessage.

func applyServerOptions

applyServerOptions sets the server options on the appropriate servers

References: caddyhttp.ServerLogConfig, fmt.Errorf, slices.Contains, slices.IndexFunc.

func automationPolicyHasAllPublicNames

automationPolicyHasAllPublicNames returns true if all the names on the policy do NOT qualify for public certs OR are tailscale domains.

References: slices.ContainsFunc.

func automationPolicyIsSubset

automationPolicyIsSubset returns true if a's subjects are a subset of b's subjects.

References: certmagic.MatchWildcard, slices.ContainsFunc.

func automationPolicyShadows

automationPolicyShadows returns the index of a policy that aps[i] shadows; in other words, for all policies after position i, if that policy covers the same subjects but is less specific, that policy's position is returned, or -1 if no shadowing is found. For example, if policy i is for "foo.example.com" and policy i+2 is for "*.example.com", then i+2 will be returned, since that policy is shadowed by i, which is in front.

func buildSubroute

buildSubroute turns the config values, which are expected to be routes into a clean and orderly subroute that has all the routes within it.

References: caddyhttp.Route, caddyhttp.Subroute, fmt.Errorf, slices.Contains, sort.Strings.

func consolidateAutomationPolicies

consolidateAutomationPolicies combines automation policies that are the same, for a cleaner overall output.

References: bytes.Equal, caddytls.AutomationPolicy, reflect.DeepEqual, slices.Contains, slices.Delete, sort.SliceStable.

func consolidateConnPolicies

consolidateConnPolicies sorts any catch-all policy to the end, removes empty TLS connection policies, and combines equivalent ones for a cleaner overall output.

References: caddytls.MatchServerName, fmt.Errorf, json.Marshal, json.Unmarshal, reflect.DeepEqual, slices.Contains, slices.Delete, sort.SliceStable.

func consolidateRoutes

consolidateRoutes combines routes with the same properties (same matchers, same Terminal and Group settings) for a cleaner overall output.

References: reflect.DeepEqual.

func detectConflictingSchemes

References: caddyhttp.DefaultHTTPPort, caddyhttp.DefaultHTTPSPort, fmt.Errorf, strconv.Itoa.

func encodeMatcherSet

References: fmt.Errorf, json.Marshal.

func fillInGlobalACMEDefaults

References: acme.EAB, caddyconfig.JSONModuleObject, caddytls.ChainPreference, caddytls.ChallengesConfig, caddytls.DNSChallengeConfig, caddytls.HTTPChallengeConfig, caddytls.TLSALPNChallengeConfig, slices.Contains.

func hostsCoveredByWildcard

References: certmagic.MatchWildcard, strings.HasPrefix.

func init

func isTailscaleDomain

References: strings.HasSuffix, strings.ToLower.

func listenersUseAnyPortOtherThan

listenersUseAnyPortOtherThan returns true if there are any listeners in addresses that use a port which is not otherPort. Mostly borrowed from unexported method in caddyhttp package.

References: strconv.Atoi.

func lowerExceptPlaceholders

lowerExceptPlaceholders lowercases s except within placeholders (substrings in non-escaped '{ }' spans). See https://github.com/caddyserver/caddy/issues/3264

References: strings.Builder, unicode.ToLower.

func mapContains

func matcherSetFromMatcherToken

References: caddyconfig.JSON, caddyhttp.MatchPath, fmt.Errorf, strings.HasPrefix.

func newBaseAutomationPolicy

newBaseAutomationPolicy returns a new TLS automation policy that gets its values from the global options map. It should be used as the base for any other automation policies. A nil policy (and no error) will be returned if there are no default/global options. However, if always is true, a non-nil value will always be returned (unless there is an error).

References: caddytls.AutomationPolicy, caddytls.InternalIssuer, certmagic.Issuer, certmagic.OCSPConfig, fmt.Errorf.

func normalizeDirectiveName

normalizeDirectiveName ensures directives that should be sorted at the same level are named the same before sorting happens.

func parseAbort

parseAbort parses the abort directive.

References: caddyhttp.StaticResponse.

func parseBind

parseBind parses the bind directive. Syntax:

	bind <addresses...> [{
   protocols [h1|h2|h2c|h3] [...]
 }]

func parseError

parseError parses the error directive.

References: caddyhttp.StaticError.

func parseFilesystem

parseFilesystem parses the fs directive. Syntax:

fs <filesystem>

References: caddyhttp.VarsMiddleware.

func parseHandle

func parseHandleErrors

References: caddyhttp.MatchExpression, caddyhttp.Subroute, fmt.Sprintf, strconv.Atoi, strings.HasSuffix, strings.Join.

func parseInvoke

parseInvoke parses the invoke directive.

References: caddyhttp.Invoke.

func parseLog

parseLog parses the log directive. Syntax:

log <logger_name> {
    hostnames <hostnames...>
    output <writer_module> ...
    core   <core_module> ...
    format <encoder_module> ...
    level  <level>
}

func parseLogHelper

parseLogHelper is used both for the parseLog directive within Server Blocks, as well as the global "log" option for configuring loggers at the global level. The parseAsGlobalOption parameter is used to distinguish any differing logic between the two.

References: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, fmt.Sprintf, reflect.DeepEqual, strconv.Atoi, time.ParseDuration, zapcore.Core, zapcore.Encoder.

func parseLogName

parseLogName parses the log_name directive. Syntax:

log_name <names...>

References: caddyhttp.AccessLoggerNameVarKey, caddyhttp.VarsMiddleware.

func parseLogOptions

parseLogOptions parses the global log option. Syntax:

log [name] {
    output  <writer_module> ...
    format  <encoder_module> ...
    level   <level>
    include <namespaces...>
    exclude <namespaces...>
}

When the name argument is unspecified, this directive modifies the default logger.

References: caddyconfig.Warning.

func parseLogSkip

parseLogSkip parses the log_skip directive. Syntax:

log_skip [<matcher>]

References: caddyhttp.VarsMiddleware.

func parseMatcherDefinitions

References: caddyconfig.JSON, caddyfile.MatcherNameCtxKey, caddyfile.NewDispenser, caddyfile.Token, caddyfile.Unmarshaler, caddyhttp.RequestMatcher, caddyhttp.RequestMatcherWithError, fmt.Errorf.

func parseMetricsOptions

func parseOCSPStaplingOptions

References: certmagic.OCSPConfig.

func parseOptACMEEAB

References: acme.EAB.

func parseOptAdmin

func parseOptAutoHTTPS

func parseOptCertIssuer

References: caddyfile.UnmarshalModule, certmagic.Issuer.

func parseOptDNS

References: caddyfile.UnmarshalModule, libdns.RecordAppender, libdns.RecordDeleter, libdns.RecordGetter, libdns.RecordSetter.

func parseOptDefaultBind

func parseOptDuration

func parseOptECH

References: caddyconfig.JSON, caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, caddytls.ECH, caddytls.ECHConfiguration, caddytls.ECHDNSPublisher, caddytls.ECHPublication.

func parseOptHTTPPort

References: strconv.Atoi.

func parseOptHTTPSPort

References: strconv.Atoi.

func parseOptOnDemand

References: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, caddytls.OnDemandConfig, caddytls.OnDemandPermission, caddytls.PermissionByHTTP.

func parseOptOrder

References: slices.DeleteFunc, slices.Index, slices.Insert.

func parseOptPersistConfig

func parseOptPreferredChains

References: caddytls.ParseCaddyfilePreferredChainsOptions.

func parseOptSingleString

func parseOptStorage

References: caddyfile.UnmarshalModule.

func parseOptTrue

func parsePKIApp

parsePKIApp parses the global log option. Syntax:

pki {
    ca [<id>] {
        name                  <name>
        root_cn               <name>
        intermediate_cn       <name>
        intermediate_lifetime <duration>
        root {
            cert   <path>
            key    <path>
            format <format>
        }
        intermediate {
            cert   <path>
            key    <path>
            format <format>
        }
    }
}

When the CA ID is unspecified, 'local' is assumed.

References: caddypki.CA, caddypki.DefaultCAID, caddypki.KeyPair, caddypki.PKI.

func parseRedir

parseRedir parses the redir directive. Syntax:

redir [<matcher>] <to> [<code>]

<code> can be "permanent" for 301, "temporary" for 302 (default), a placeholder, or any number in the 3xx range or 401. The special code "html" can be used to redirect only browser clients (will respond with HTTP 200 and no Location header; redirect is performed with JS and a meta tag).

References: caddyhttp.StaticResponse, caddyhttp.WeakString, fmt.Sprintf, html.EscapeString, http.Header, strconv.Atoi, strings.HasPrefix.

func parseRespond

parseRespond parses the respond directive.

References: caddyhttp.StaticResponse.

func parseRoot

parseRoot parses the root directive. Syntax:

root [<matcher>] <path>

References: caddyhttp.VarsMiddleware.

func parseRoute

parseRoute parses the route directive.

References: caddyhttp.Route, caddyhttp.Subroute.

func parseSegmentAsConfig

parseSegmentAsConfig parses the segment such that its subdirectives are themselves treated as directives, including named matcher definitions, and the raw Config structs are returned.

References: caddyfile.NewDispenser, caddyfile.Segment, maps.Copy, strings.HasPrefix.

func parseServerOptions

func parseStorageCheck

func parseStorageCleanInterval

func parseTLS

parseTLS parses the tls directive. Syntax:

tls [<email>|internal|force_automate]|[<cert_file> <key_file>] {
    protocols <min> [<max>]
    ciphers   <cipher_suites...>
    curves    <curves...>
    client_auth {
        mode                   [request|require|verify_if_given|require_and_verify]
        trust_pool			   <module_name> [...]
        trusted_leaf_cert      <base64_der>
        trusted_leaf_cert_file <filename>
    }
    alpn                          <values...>
    load                          <paths...>
    ca                            <acme_ca_endpoint>
    ca_root                       <pem_file>
    key_type                      [ed25519|p256|p384|rsa2048|rsa4096]
    dns                           [<provider_name> [...]]    (required, though, if DNS is not configured as global option)
    propagation_delay             <duration>
    propagation_timeout           <duration>
    resolvers                     <dns_servers...>
    dns_ttl                       <duration>
    dns_challenge_override_domain <domain>
    on_demand
    reuse_private_keys
    force_automate
    eab                           <key_id> <mac_key>
    issuer                        <module_name> [...]
    get_certificate               <module_name> [...]
    insecure_secrets_log          <log_file>
}

References: acme.EAB, caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, caddytls.ACMEIssuer, caddytls.CertKeyFilePair, caddytls.ChallengesConfig, caddytls.CipherSuiteNameSupported, caddytls.ClientAuthentication, caddytls.ConnectionPolicy, caddytls.CustomCertSelectionPolicy, caddytls.DNSChallengeConfig, caddytls.DefaultIssuers, caddytls.FileLoader, caddytls.FolderLoader, caddytls.InternalIssuer, caddytls.SupportedCurves, caddytls.SupportedProtocols, certmagic.Issuer, certmagic.Manager, fmt.Sprintf, strings.Contains, time.Duration.

func parseVars

parseVars parses the vars directive. See its UnmarshalCaddyfile method for syntax.

References: caddyhttp.VarsMiddleware.

func placeholderShorthands

placeholderShorthands returns a slice of old-new string pairs, where the left of the pair is a placeholder shorthand that may be used in the Caddyfile, and the right is the replacement.

func sortRoutes

References: caddyhttp.MatchPath, caddyhttp.Route, json.Unmarshal, sort.SliceStable, strings.TrimSuffix.

func specificity

specificity returns len(s) minus any wildcards () and placeholders ({...}). Basically, it's a length count that penalizes the use of wildcards and placeholders. This is useful for comparing hostnames and paths. However, wildcards in paths are not a sure answer to the question of specificity. For example, '.example.com' is clearly less specific than 'a.example.com', but is '/a' more or less specific than '/a*'?

References: strings.Count, strings.Index.

func subjectQualifiesForPublicCert

subjectQualifiesForPublicCert is like certmagic.SubjectQualifiesForPublicCert() except that this allows domains with multiple wildcard levels like '..example.com' to qualify if the automation policy has OnDemand enabled (i.e. this function is more lenient).

IP subjects are considered as non-qualifying for public certs. Technically, there are now public ACME CAs as well as non-ACME CAs that issue IP certificates. But this function is used solely for implicit automation (defaults), where it gets really complicated to keep track of which issuers support IP certificates in which circumstances. Currently, issuers that support IP certificates are very few, and all require some sort of config from the user anyway (such as an account credential). Since we cannot implicitly and automatically get public IP certs without configuration from the user, we treat IPs as not qualifying for public certificates. Users should expressly configure an issuer that supports IP certs for that purpose.

References: certmagic.SubjectIsIP, certmagic.SubjectIsInternal, strings.Count.

func tryDuration

References: caddyconfig.Warning.

func tryInt

tryInt tries to convert val to an integer. If it fails, it downgrades the error to a warning and returns 0.

References: caddyconfig.Warning.

func tryString

References: caddyconfig.Warning.

func unmarshalCaddyfileMetricsOptions

References: caddyhttp.Metrics.

func unmarshalCaddyfileServerOptions

References: caddyconfig.JSONModuleObject, caddyfile.UnmarshalModule, caddyhttp.IPRangeSource, caddyhttp.Metrics, fmt.Errorf, humanize.ParseBytes, slices.Contains.

func compileEncodedMatcherSets

References: caddyhttp.MatchHost, caddyhttp.MatchPath, caddyhttp.RequestMatcherWithError, fmt.Errorf, slices.Contains.

func consolidateAddrMappings

consolidateAddrMappings eliminates repetition of identical server blocks in a mapping of single listener addresses to protocols to lists of server blocks. Since multiple addresses may serve multiple protocols to identical sites (server block contents), this function turns a 1:many mapping into a many:many mapping. Server block contents (tokens) must be exactly identical so that reflect.DeepEqual returns true in order for the addresses to be combined. Identical entries are deleted from the addrToServerBlocks map. Essentially, each pairing (each association from multiple addresses to multiple server blocks; i.e. each element of the returned slice) becomes a server definition in the output JSON.

References: reflect.DeepEqual, sort.Strings.

func listenersForServerBlockAddress

listenersForServerBlockAddress essentially converts the Caddyfile site addresses to a map from Caddy listener addresses and the protocols to serve them with to the parsed address for each server block.

References: caddyhttp.DefaultHTTPPort, caddyhttp.DefaultHTTPSPort, fmt.Errorf, strconv.Itoa.

func mapAddressToProtocolToServerBlocks

mapAddressToProtocolToServerBlocks returns a map of listener address to list of server blocks that will be served on that address. To do this, each server block is expanded so that each one is considered individually, although keys of a server block that share the same address stay grouped together so the config isn't repeated unnecessarily. For example, this Caddyfile:

example.com {
	bind 127.0.0.1
}
www.example.com, example.net/path, localhost:9999 {
	bind 127.0.0.1 1.2.3.4
}

has two server blocks to start with. But expressed in this Caddyfile are actually 4 listener addresses: 127.0.0.1:443, 1.2.3.4:443, 127.0.0.1:9999, and 127.0.0.1:9999. This is because the bind directive is applied to each key of its server block (specifying the host part), and each key may have a different port. And we definitely need to be sure that a site which is bound to be served on a specific interface is not served on others just because that is more convenient: it would be a potential security risk if the difference between interfaces means private vs. public.

So what this function does for the example above is iterate each server block, and for each server block, iterate its keys. For the first, it finds one key (example.com) and determines its listener address (127.0.0.1:443 - because of 'bind' and automatic HTTPS). It then adds the listener address to the map value returned by this function, with the first server block as one of its associations.

It then iterates each key on the second server block and associates them with one or more listener addresses. Indeed, each key in this block has two listener addresses because of the 'bind' directive. Once we know which addresses serve which keys, we can create a new server block for each address containing the contents of the server block and only those specific keys of the server block which use that address.

It is possible and even likely that some keys in the returned map have the exact same list of server blocks (i.e. they are identical). This happens when multiple hosts are declared with a 'bind' directive and the resulting listener addresses are not shared by any other server block (or the other server blocks are exactly identical in their token contents). This happens with our example above because 1.2.3.4:443 and 1.2.3.4:9999 are used exclusively with the second server block. This repetition may be undesirable, so call consolidateAddrMappings() to map multiple addresses to the same lists of server blocks (a many:many mapping). (Doing this is essentially a map-reduce technique.)

References: caddyfile.ServerBlock, caddyfile.Token, fmt.Errorf, sort.Strings.

func serversFromPairings

serversFromPairings creates the servers for each pairing of addresses to server blocks. Each pairing is essentially a server definition.

References: caddyconfig.JSON, caddyconfig.JSONModuleObject, caddyhttp.AutoHTTPSConfig, caddyhttp.DefaultHTTPPort, caddyhttp.DefaultHTTPSPort, caddyhttp.HTTPErrorConfig, caddyhttp.Route, caddyhttp.Server, caddyhttp.ServerLogConfig, caddyhttp.StringArray, caddyhttp.Subroute, caddytls.ConnectionPolicy, fmt.Errorf, fmt.Sprintf, net.SplitHostPort, slices.Contains, slices.Sort, sort.SliceStable, strconv.Itoa, strings.Contains, zap.String.

func buildPKIApp

References: caddypki.CA, caddypki.DefaultCAID, caddypki.PKI.

func buildTLSApp

References: caddyconfig.JSON, caddyconfig.JSONModuleObject, caddyhttp.DefaultHTTPPort, caddytls.ACMEIssuer, caddytls.AutomateLoader, caddytls.AutomationConfig, caddytls.AutomationPolicy, caddytls.CertificateLoader, caddytls.ChallengesConfig, caddytls.DefaultIssuers, caddytls.ECH, caddytls.InternalIssuer, caddytls.OnDemandConfig, caddytls.TLS, certmagic.Issuer, certmagic.OCSPConfig, certmagic.SubjectQualifiesForCert, certmagic.SubjectQualifiesForPublicCert, fmt.Errorf, json.RawMessage, reflect.Append, reflect.DeepEqual, reflect.New, reflect.Slice, reflect.TypeOf, reflect.ValueOf, slices.Contains, slices.Sort, sort.Strings, strconv.Itoa, strings.HasPrefix.

func evaluateGlobalOptionsBlock

evaluateGlobalOptionsBlock evaluates the global options block, which is expected to be the first server block if it has zero keys. It returns the updated list of server blocks with the global options block removed, and updates options accordingly.

References: caddyfile.NewDispenser, fmt.Errorf, sort.Slice.

func extractNamedRoutes

extractNamedRoutes pulls out any named route server blocks so they don't get parsed as sites, and stores them in options for later.

References: caddyconfig.JSONModuleObject, caddyfile.NewDispenser, caddyfile.Segment, caddyhttp.Route, caddyhttp.Subroute, json.RawMessage.

func nextGroup

References: fmt.Sprintf.

func hasHostCatchAllKey

hasHostCatchAllKey returns true if sb has a key that omits a host portion, i.e. it "catches all" hosts.

References: slices.ContainsFunc.

func hostsFromKeys

hostsFromKeys returns a list of all the non-empty hostnames found in the keys of the server block sb. If logger mode is false, a key with an empty hostname portion will return an empty slice, since that server block is interpreted to effectively match all hosts. An empty string is never added to the slice.

If loggerMode is true, then the non-standard ports of keys will be joined to the hostnames. This is to effectively match the Host header of requests that come in for that key.

The resulting slice is not sorted but will never have duplicates.

References: caddyhttp.DefaultHTTPPort, caddyhttp.DefaultHTTPSPort, net.JoinHostPort, strconv.Itoa.

func hostsFromKeysNotHTTP

func isAllHTTP

isAllHTTP returns true if all sb keys explicitly specify the http:// scheme

References: slices.ContainsFunc.


Tests

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

Test functions

TestAddressString

TestAutomationPolicyIsSubset

References: caddytls.AutomationPolicy.

TestGlobalLogOptionSyntax

References: caddyfile.Adapter.

TestGlobalOptions

References: caddyfile.Adapter.

TestHostsFromKeys

References: reflect.DeepEqual, sort.Strings.

TestImportErrorLine

References: caddyfile.Adapter, strings.Contains.

TestKeyNormalization

TestLogDirectiveSyntax

References: caddyfile.Adapter.

TestMatcherSyntax

References: caddyfile.Adapter.

TestNestedImport

References: caddyfile.Adapter.

TestParseAddress

TestRedirDirectiveSyntax

References: caddyfile.Adapter.

TestSpecificity