Documentation ¶
Index ¶
- Constants
- Variables
- func GetVar(ctx context.Context, key string) interface{}
- func NewTestReplacer(req *http.Request) *caddy.Replacer
- func PrepareRequest(r *http.Request, repl *caddy.Replacer, w http.ResponseWriter, s *Server) *http.Request
- func SetVar(ctx context.Context, key string, value interface{})
- func StatusCodeMatches(actual, configured int) bool
- type App
- type AutoHTTPSConfig
- type HTTPErrorConfig
- type HTTPInterfaces
- type Handler
- type HandlerError
- type HandlerFunc
- type LoggableHTTPHeader
- type LoggableHTTPRequest
- type LoggableStringArray
- type LoggableTLSConnState
- type MatchExpression
- func (MatchExpression) CaddyModule() caddy.ModuleInfo
- func (m MatchExpression) MarshalJSON() ([]byte, error)
- func (m MatchExpression) Match(r *http.Request) bool
- func (m *MatchExpression) Provision(_ caddy.Context) error
- func (m *MatchExpression) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- func (m *MatchExpression) UnmarshalJSON(data []byte) error
- type MatchHeader
- type MatchHeaderRE
- type MatchHost
- type MatchMethod
- type MatchNot
- func (MatchNot) CaddyModule() caddy.ModuleInfo
- func (m MatchNot) MarshalJSON() ([]byte, error)
- func (m MatchNot) Match(r *http.Request) bool
- func (m *MatchNot) Provision(ctx caddy.Context) error
- func (m *MatchNot) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- func (m *MatchNot) UnmarshalJSON(data []byte) error
- type MatchPath
- type MatchPathRE
- type MatchProtocol
- type MatchQuery
- type MatchRegexp
- type MatchRemoteIP
- type MatchVarsRE
- type MatcherSet
- type MatcherSets
- type Middleware
- type MiddlewareHandler
- type RawMatcherSets
- type RequestMatcher
- type ResponseHandler
- type ResponseMatcher
- type ResponseRecorder
- type ResponseWriterWrapper
- type Route
- type RouteList
- type Server
- type ServerLogConfig
- type ShouldBufferFunc
- type StaticError
- type StaticResponse
- type Subroute
- type VarsMatcher
- type VarsMiddleware
- type WeakString
Constants ¶
const ( // DefaultHTTPPort is the default port for HTTP. DefaultHTTPPort = 80 // DefaultHTTPSPort is the default port for HTTPS. DefaultHTTPSPort = 443 )
const ( // For referencing the server instance ServerCtxKey caddy.CtxKey = "server" // For the request's variable table VarsCtxKey caddy.CtxKey = "vars" // For a partial copy of the unmodified request that // originally came into the server's entry handler OriginalRequestCtxKey caddy.CtxKey = "original_request" )
Context keys for HTTP request context values.
const ErrorCtxKey = caddy.CtxKey("handler_chain_error")
ErrorCtxKey is the context key to use when storing an error (for use with context.Context).
Variables ¶
var ErrNotImplemented = fmt.Errorf("method not implemented")
ErrNotImplemented is returned when an underlying ResponseWriter does not implement the required method.
Functions ¶
func GetVar ¶
GetVar gets a value out of the context's variable table by key. If the key does not exist, the return value will be nil.
func NewTestReplacer ¶
NewTestReplacer creates a replacer for an http.Request for use in tests that are not in this package
func PrepareRequest ¶
func PrepareRequest(r *http.Request, repl *caddy.Replacer, w http.ResponseWriter, s *Server) *http.Request
PrepareRequest fills the request r for use in a Caddy HTTP handler chain. w and s can be nil, but the handlers will lose response placeholders and access to the server.
func SetVar ¶
SetVar sets a value in the context's variable table with the given key. It overwrites any previous value with the same key.
func StatusCodeMatches ¶
StatusCodeMatches returns true if a real HTTP status code matches the configured status code, which may be either a real HTTP status code or an integer representing a class of codes (e.g. 4 for all 4xx statuses).
Types ¶
type App ¶
type App struct { // HTTPPort specifies the port to use for HTTP (as opposed to HTTPS), // which is used when setting up HTTP->HTTPS redirects or ACME HTTP // challenge solvers. Default: 80. HTTPPort int `json:"http_port,omitempty"` // HTTPSPort specifies the port to use for HTTPS, which is used when // solving the ACME TLS-ALPN challenges, or whenever HTTPS is needed // but no specific port number is given. Default: 443. HTTPSPort int `json:"https_port,omitempty"` // GracePeriod is how long to wait for active connections when shutting // down the server. Once the grace period is over, connections will // be forcefully closed. GracePeriod caddy.Duration `json:"grace_period,omitempty"` // Servers is the list of servers, keyed by arbitrary names chosen // at your discretion for your own convenience; the keys do not // affect functionality. Servers map[string]*Server `json:"servers,omitempty"` // contains filtered or unexported fields }
App is a robust, production-ready HTTP server.
HTTPS is enabled by default if host matchers with qualifying names are used in any of routes; certificates are automatically provisioned and renewed. Additionally, automatic HTTPS will also enable HTTPS for servers that listen only on the HTTPS port but which do not have any TLS connection policies defined by adding a good, default TLS connection policy.
In HTTP routes, additional placeholders are available (replace any `*`):
Placeholder | Description ------------|--------------- `{http.request.body}` | The request body (⚠️ inefficient; use only for debugging) `{http.request.cookie.*}` | HTTP request cookie `{http.request.duration}` | Time up to now spent handling the request (after decoding headers from client) `{http.request.header.*}` | Specific request header field `{http.request.host.labels.*}` | Request host labels (0-based from right); e.g. for foo.example.com: 0=com, 1=example, 2=foo `{http.request.host}` | The host part of the request's Host header `{http.request.hostport}` | The host and port from the request's Host header `{http.request.method}` | The request method `{http.request.orig_method}` | The request's original method `{http.request.orig_uri.path.dir}` | The request's original directory `{http.request.orig_uri.path.file}` | The request's original filename `{http.request.orig_uri.path}` | The request's original path `{http.request.orig_uri.query}` | The request's original query string (without `?`) `{http.request.orig_uri}` | The request's original URI `{http.request.port}` | The port part of the request's Host header `{http.request.proto}` | The protocol of the request `{http.request.remote.host}` | The host part of the remote client's address `{http.request.remote.port}` | The port part of the remote client's address `{http.request.remote}` | The address of the remote client `{http.request.scheme}` | The request scheme `{http.request.tls.version}` | The TLS version name `{http.request.tls.cipher_suite}` | The TLS cipher suite `{http.request.tls.resumed}` | The TLS connection resumed a previous connection `{http.request.tls.proto}` | The negotiated next protocol `{http.request.tls.proto_mutual}` | The negotiated next protocol was advertised by the server `{http.request.tls.server_name}` | The server name requested by the client, if any `{http.request.tls.client.fingerprint}` | The SHA256 checksum of the client certificate `{http.request.tls.client.public_key}` | The public key of the client certificate. `{http.request.tls.client.public_key_sha256}` | The SHA256 checksum of the client's public key. `{http.request.tls.client.certificate_pem}` | The PEM-encoded value of the certificate. `{http.request.tls.client.issuer}` | The issuer DN of the client certificate `{http.request.tls.client.serial}` | The serial number of the client certificate `{http.request.tls.client.subject}` | The subject DN of the client certificate `{http.request.tls.client.san.dns_names.*}` | SAN DNS names(index optional) `{http.request.tls.client.san.emails.*}` | SAN email addresses (index optional) `{http.request.tls.client.san.ips.*}` | SAN IP addresses (index optional) `{http.request.tls.client.san.uris.*}` | SAN URIs (index optional) `{http.request.uri.path.*}` | Parts of the path, split by `/` (0-based from left) `{http.request.uri.path.dir}` | The directory, excluding leaf filename `{http.request.uri.path.file}` | The filename of the path, excluding directory `{http.request.uri.path}` | The path component of the request URI `{http.request.uri.query.*}` | Individual query string value `{http.request.uri.query}` | The query string (without `?`) `{http.request.uri}` | The full request URI `{http.response.header.*}` | Specific response header field `{http.vars.*}` | Custom variables in the HTTP handler chain
func (App) CaddyModule ¶
func (App) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
type AutoHTTPSConfig ¶
type AutoHTTPSConfig struct { // If true, automatic HTTPS will be entirely disabled. Disabled bool `json:"disable,omitempty"` // If true, only automatic HTTP->HTTPS redirects will // be disabled. DisableRedir bool `json:"disable_redirects,omitempty"` // Hosts/domain names listed here will not be included // in automatic HTTPS (they will not have certificates // loaded nor redirects applied). Skip []string `json:"skip,omitempty"` // Hosts/domain names listed here will still be enabled // for automatic HTTPS (unless in the Skip list), except // that certificates will not be provisioned and managed // for these names. SkipCerts []string `json:"skip_certificates,omitempty"` // By default, automatic HTTPS will obtain and renew // certificates for qualifying hostnames. However, if // a certificate with a matching SAN is already loaded // into the cache, certificate management will not be // enabled. To force automated certificate management // regardless of loaded certificates, set this to true. IgnoreLoadedCerts bool `json:"ignore_loaded_certificates,omitempty"` }
AutoHTTPSConfig is used to disable automatic HTTPS or certain aspects of it for a specific server. HTTPS is enabled automatically and by default when qualifying hostnames are available from the config.
type HTTPErrorConfig ¶
type HTTPErrorConfig struct { // The routes to evaluate after the primary handler // chain returns an error. In an error route, extra // placeholders are available: // // Placeholder | Description // ------------|--------------- // `{http.error.status_code}` | The recommended HTTP status code // `{http.error.status_text}` | The status text associated with the recommended status code // `{http.error.message}` | The error message // `{http.error.trace}` | The origin of the error // `{http.error.id}` | An identifier for this occurrence of the error Routes RouteList `json:"routes,omitempty"` }
HTTPErrorConfig determines how to handle errors from the HTTP handlers.
func (*HTTPErrorConfig) WithError ¶
WithError makes a shallow copy of r to add the error to its context, and sets placeholders on the request's replacer related to err. It returns the modified request which has the error information in its context and replacer. It overwrites any existing error values that are stored.
type HTTPInterfaces ¶
HTTPInterfaces mix all the interfaces that middleware ResponseWriters need to support.
type Handler ¶
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request) error
}
Handler is like http.Handler except ServeHTTP may return an error.
If any handler encounters an error, it should be returned for proper handling. Return values should be propagated down the middleware chain by returning it unchanged. Returned errors should not be re-wrapped if they are already HandlerError values.
type HandlerError ¶
type HandlerError struct { Err error // the original error value and message StatusCode int // the HTTP status code to associate with this error ID string // generated; for identifying this error in logs Trace string // produced from call stack }
HandlerError is a serializable representation of an error from within an HTTP handler.
func Error ¶
func Error(statusCode int, err error) HandlerError
Error is a convenient way for a Handler to populate the essential fields of a HandlerError. If err is itself a HandlerError, then any essential fields that are not set will be populated.
func (HandlerError) Error ¶
func (e HandlerError) Error() string
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, *http.Request) error
HandlerFunc is a convenience type like http.HandlerFunc.
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error
ServeHTTP implements the Handler interface.
type LoggableHTTPHeader ¶
LoggableHTTPHeader makes an HTTP header loggable with zap.Object().
func (LoggableHTTPHeader) MarshalLogObject ¶
func (h LoggableHTTPHeader) MarshalLogObject(enc zapcore.ObjectEncoder) error
MarshalLogObject satisfies the zapcore.ObjectMarshaler interface.
type LoggableHTTPRequest ¶
LoggableHTTPRequest makes an HTTP request loggable with zap.Object().
func (LoggableHTTPRequest) MarshalLogObject ¶
func (r LoggableHTTPRequest) MarshalLogObject(enc zapcore.ObjectEncoder) error
MarshalLogObject satisfies the zapcore.ObjectMarshaler interface.
type LoggableStringArray ¶
type LoggableStringArray []string
LoggableStringArray makes a slice of strings marshalable for logging.
func (LoggableStringArray) MarshalLogArray ¶
func (sa LoggableStringArray) MarshalLogArray(enc zapcore.ArrayEncoder) error
MarshalLogArray satisfies the zapcore.ArrayMarshaler interface.
type LoggableTLSConnState ¶
type LoggableTLSConnState tls.ConnectionState
LoggableTLSConnState makes a TLS connection state loggable with zap.Object().
func (LoggableTLSConnState) MarshalLogObject ¶
func (t LoggableTLSConnState) MarshalLogObject(enc zapcore.ObjectEncoder) error
MarshalLogObject satisfies the zapcore.ObjectMarshaler interface.
type MatchExpression ¶
type MatchExpression struct { // The CEL expression to evaluate. Any Caddy placeholders // will be expanded and situated into proper CEL function // calls before evaluating. Expr string // contains filtered or unexported fields }
MatchExpression matches requests by evaluating a [CEL](https://github.com/google/cel-spec) expression. This enables complex logic to be expressed using a comfortable, familiar syntax. Please refer to [the standard definitions of CEL functions and operators](https://github.com/google/cel-spec/blob/master/doc/langdef.md#standard-definitions).
This matcher's JSON interface is actually a string, not a struct. The generated docs are not correct because this type has custom marshaling logic.
COMPATIBILITY NOTE: This module is still experimental and is not subject to Caddy's compatibility guarantee.
func (MatchExpression) CaddyModule ¶
func (MatchExpression) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchExpression) MarshalJSON ¶
func (m MatchExpression) MarshalJSON() ([]byte, error)
MarshalJSON marshals m's expression.
func (MatchExpression) Match ¶
func (m MatchExpression) Match(r *http.Request) bool
Match returns true if r matches m.
func (*MatchExpression) Provision ¶
func (m *MatchExpression) Provision(_ caddy.Context) error
Provision sets ups m.
func (*MatchExpression) UnmarshalCaddyfile ¶
func (m *MatchExpression) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (*MatchExpression) UnmarshalJSON ¶
func (m *MatchExpression) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshals m's expression.
type MatchHeader ¶
MatchHeader matches requests by header fields. It performs fast, exact string comparisons of the field values. Fast prefix, suffix, and substring matches can also be done by suffixing, prefixing, or surrounding the value with the wildcard `*` character, respectively. If a list is null, the header must not exist. If the list is empty, the field must simply exist, regardless of its value.
func (MatchHeader) CaddyModule ¶
func (MatchHeader) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchHeader) Match ¶
func (m MatchHeader) Match(r *http.Request) bool
Match returns true if r matches m.
func (*MatchHeader) UnmarshalCaddyfile ¶
func (m *MatchHeader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type MatchHeaderRE ¶
type MatchHeaderRE map[string]*MatchRegexp
MatchHeaderRE matches requests by a regular expression on header fields.
Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` where `name` is the regular expression's name, and `capture_group` is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: `{http.regexp.capture_group}` (potentially leading to collisions).
func (MatchHeaderRE) CaddyModule ¶
func (MatchHeaderRE) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchHeaderRE) Match ¶
func (m MatchHeaderRE) Match(r *http.Request) bool
Match returns true if r matches m.
func (MatchHeaderRE) Provision ¶
func (m MatchHeaderRE) Provision(ctx caddy.Context) error
Provision compiles m's regular expressions.
func (*MatchHeaderRE) UnmarshalCaddyfile ¶
func (m *MatchHeaderRE) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (MatchHeaderRE) Validate ¶
func (m MatchHeaderRE) Validate() error
Validate validates m's regular expressions.
type MatchHost ¶
type MatchHost []string
MatchHost matches requests by the Host value (case-insensitive).
When used in a top-level HTTP route, [qualifying domain names](/docs/automatic-https#hostname-requirements) may trigger [automatic HTTPS](/docs/automatic-https), which automatically provisions and renews certificates for you. Before doing this, you should ensure that DNS records for these domains are properly configured, especially A/AAAA pointed at your server.
Automatic HTTPS can be [customized or disabled](/docs/modules/http#servers/automatic_https).
Wildcards (`*`) may be used to represent exactly one label of the hostname, in accordance with RFC 1034 (because host matchers are also used for automatic HTTPS which influences TLS certificates). Thus, a host of `*` matches hosts like `localhost` or `internal` but not `example.com`. To catch all hosts, omit the host matcher entirely.
The wildcard can be useful for matching all subdomains, for example: `*.example.com` matches `foo.example.com` but not `foo.bar.example.com`.
Duplicate entries will return an error.
func (MatchHost) CaddyModule ¶
func (MatchHost) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
type MatchMethod ¶
type MatchMethod []string
MatchMethod matches requests by the method.
func (MatchMethod) CaddyModule ¶
func (MatchMethod) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchMethod) Match ¶
func (m MatchMethod) Match(r *http.Request) bool
Match returns true if r matches m.
func (*MatchMethod) UnmarshalCaddyfile ¶
func (m *MatchMethod) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type MatchNot ¶
type MatchNot struct { MatcherSetsRaw []caddy.ModuleMap `json:"-" caddy:"namespace=http.matchers"` MatcherSets []MatcherSet `json:"-"` }
MatchNot matches requests by negating the results of its matcher sets. A single "not" matcher takes one or more matcher sets. Each matcher set is OR'ed; in other words, if any matcher set returns true, the final result of the "not" matcher is false. Individual matchers within a set work the same (i.e. different matchers in the same set are AND'ed).
Note that the generated docs which describe the structure of this module are wrong because of how this type unmarshals JSON in a custom way. The correct structure is:
```json [
{}, {}
] ```
where each of the array elements is a matcher set, i.e. an object keyed by matcher name.
func (MatchNot) CaddyModule ¶
func (MatchNot) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchNot) MarshalJSON ¶
MarshalJSON satisfies json.Marshaler by marshaling m's raw matcher sets.
func (MatchNot) Match ¶
Match returns true if r matches m. Since this matcher negates the embedded matchers, false is returned if any of its matcher sets return true.
func (*MatchNot) UnmarshalCaddyfile ¶
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (*MatchNot) UnmarshalJSON ¶
UnmarshalJSON satisfies json.Unmarshaler. It puts the JSON bytes directly into m's MatcherSetsRaw field.
type MatchPath ¶
type MatchPath []string
MatchPath matches requests by the URI's path (case-insensitive). Path matches are exact, but wildcards may be used:
- At the end, for a prefix match (`/prefix/*`) - At the beginning, for a suffix match (`*.suffix`) - On both sides, for a substring match (`*/contains/*`) - In the middle, for a globular match (`/accounts/*/info`)
This matcher is fast, so it does not support regular expressions or capture groups. For slower but more powerful matching, use the path_regexp matcher.
func (MatchPath) CaddyModule ¶
func (MatchPath) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
type MatchPathRE ¶
type MatchPathRE struct{ MatchRegexp }
MatchPathRE matches requests by a regular expression on the URI's path.
Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` where `name` is the regular expression's name, and `capture_group` is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: `{http.regexp.capture_group}` (potentially leading to collisions).
func (MatchPathRE) CaddyModule ¶
func (MatchPathRE) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
type MatchProtocol ¶
type MatchProtocol string
MatchProtocol matches requests by protocol.
func (MatchProtocol) CaddyModule ¶
func (MatchProtocol) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchProtocol) Match ¶
func (m MatchProtocol) Match(r *http.Request) bool
Match returns true if r matches m.
func (*MatchProtocol) UnmarshalCaddyfile ¶
func (m *MatchProtocol) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type MatchQuery ¶
MatchQuery matches requests by URI's query string.
func (MatchQuery) CaddyModule ¶
func (MatchQuery) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchQuery) Match ¶
func (m MatchQuery) Match(r *http.Request) bool
Match returns true if r matches m. An empty m matches an empty query string.
func (*MatchQuery) UnmarshalCaddyfile ¶
func (m *MatchQuery) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type MatchRegexp ¶
type MatchRegexp struct { // A unique name for this regular expression. Optional, // but useful to prevent overwriting captures from other // regexp matchers. Name string `json:"name,omitempty"` // The regular expression to evaluate, in RE2 syntax, // which is the same general syntax used by Go, Perl, // and Python. For details, see // [Go's regexp package](https://golang.org/pkg/regexp/). // Captures are accessible via placeholders. Unnamed // capture groups are exposed as their numeric, 1-based // index, while named capture groups are available by // the capture group name. Pattern string `json:"pattern"` // contains filtered or unexported fields }
MatchRegexp is an embedable type for matching using regular expressions. It adds placeholders to the request's replacer.
func (*MatchRegexp) Match ¶
func (mre *MatchRegexp) Match(input string, repl *caddy.Replacer) bool
Match returns true if input matches the compiled regular expression in mre. It sets values on the replacer repl associated with capture groups, using the given scope (namespace).
func (*MatchRegexp) Provision ¶
func (mre *MatchRegexp) Provision(caddy.Context) error
Provision compiles the regular expression.
func (*MatchRegexp) UnmarshalCaddyfile ¶
func (mre *MatchRegexp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (*MatchRegexp) Validate ¶
func (mre *MatchRegexp) Validate() error
Validate ensures mre is set up correctly.
type MatchRemoteIP ¶
type MatchRemoteIP struct { // The IPs or CIDR ranges to match. Ranges []string `json:"ranges,omitempty"` // If true, prefer the first IP in the request's X-Forwarded-For // header, if present, rather than the immediate peer's IP, as // the reference IP against which to match. Note that it is easy // to spoof request headers. Default: false Forwarded bool `json:"forwarded,omitempty"` // contains filtered or unexported fields }
MatchRemoteIP matches requests by client IP (or CIDR range).
func (MatchRemoteIP) CaddyModule ¶
func (MatchRemoteIP) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchRemoteIP) Match ¶
func (m MatchRemoteIP) Match(r *http.Request) bool
Match returns true if r matches m.
func (*MatchRemoteIP) Provision ¶
func (m *MatchRemoteIP) Provision(ctx caddy.Context) error
Provision parses m's IP ranges, either from IP or CIDR expressions.
func (*MatchRemoteIP) UnmarshalCaddyfile ¶
func (m *MatchRemoteIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type MatchVarsRE ¶
type MatchVarsRE map[string]*MatchRegexp
MatchVarsRE matches the value of the context variables by a given regular expression.
Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` where `name` is the regular expression's name, and `capture_group` is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: `{http.regexp.capture_group}` (potentially leading to collisions).
func (MatchVarsRE) CaddyModule ¶
func (MatchVarsRE) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchVarsRE) Match ¶
func (m MatchVarsRE) Match(r *http.Request) bool
Match returns true if r matches m.
func (MatchVarsRE) Provision ¶
func (m MatchVarsRE) Provision(ctx caddy.Context) error
Provision compiles m's regular expressions.
func (*MatchVarsRE) UnmarshalCaddyfile ¶
func (m *MatchVarsRE) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (MatchVarsRE) Validate ¶
func (m MatchVarsRE) Validate() error
Validate validates m's regular expressions.
type MatcherSet ¶
type MatcherSet []RequestMatcher
MatcherSet is a set of matchers which must all match in order for the request to be matched successfully.
type MatcherSets ¶
type MatcherSets []MatcherSet
MatcherSets is a group of matcher sets capable of checking whether a request matches any of the sets.
func (MatcherSets) AnyMatch ¶
func (ms MatcherSets) AnyMatch(req *http.Request) bool
AnyMatch returns true if req matches any of the matcher sets in ms or if there are no matchers, in which case the request always matches.
func (*MatcherSets) FromInterface ¶
func (ms *MatcherSets) FromInterface(matcherSets interface{}) error
FromInterface fills ms from an interface{} value obtained from LoadModule.
type Middleware ¶
Middleware chains one Handler to the next by being passed the next Handler in the chain.
type MiddlewareHandler ¶
MiddlewareHandler is like Handler except it takes as a third argument the next handler in the chain. The next handler will never be nil, but may be a no-op handler if this is the last handler in the chain. Handlers which act as middleware should call the next handler's ServeHTTP method so as to propagate the request down the chain properly. Handlers which act as responders (content origins) need not invoke the next handler, since the last handler in the chain should be the first to write the response.
type RawMatcherSets ¶
type RawMatcherSets []caddy.ModuleMap
RawMatcherSets is a group of matcher sets in their raw, JSON form.
type RequestMatcher ¶
RequestMatcher is a type that can match to a request. A route matcher MUST NOT modify the request, with the only exception being its context.
type ResponseHandler ¶
type ResponseHandler struct { // The response matcher for this handler. If empty/nil, // it always matches. Match *ResponseMatcher `json:"match,omitempty"` // To write the original response body but with a different // status code, set this field to the desired status code. // If set, this takes priority over routes. StatusCode WeakString `json:"status_code,omitempty"` // The list of HTTP routes to execute if no status code is // specified. If evaluated, the original response body // will not be written. Routes RouteList `json:"routes,omitempty"` }
ResponseHandler pairs a response matcher with custom handling logic. Either the status code can be changed to something else while using the original response body, or, if a status code is not set, it can execute a custom route list; this is useful for executing handler routes based on the properties of an HTTP response that has not been written out to the client yet.
To use this type, provision it at module load time, then when ready to use, match the response against its matcher; if it matches (or doesn't have a matcher), change the status code on the response if configured; otherwise invoke the routes by calling `rh.Routes.Compile(next).ServeHTTP(rw, req)` (or similar).
func (*ResponseHandler) Provision ¶
func (rh *ResponseHandler) Provision(ctx caddy.Context) error
Provision sets up the routse in rh.
type ResponseMatcher ¶
type ResponseMatcher struct { // If set, one of these status codes would be required. // A one-digit status can be used to represent all codes // in that class (e.g. 3 for all 3xx codes). StatusCode []int `json:"status_code,omitempty"` // If set, each header specified must be one of the // specified values, with the same logic used by the // request header matcher. Headers http.Header `json:"headers,omitempty"` }
ResponseMatcher is a type which can determine if an HTTP response matches some criteria.
type ResponseRecorder ¶
type ResponseRecorder interface { HTTPInterfaces Status() int Buffer() *bytes.Buffer Buffered() bool Size() int WriteResponse() error }
ResponseRecorder is a http.ResponseWriter that records responses instead of writing them to the client. See docs for NewResponseRecorder for proper usage.
func NewResponseRecorder ¶
func NewResponseRecorder(w http.ResponseWriter, buf *bytes.Buffer, shouldBuffer ShouldBufferFunc) ResponseRecorder
NewResponseRecorder returns a new ResponseRecorder that can be used instead of a standard http.ResponseWriter. The recorder is useful for middlewares which need to buffer a response and potentially process its entire body before actually writing the response to the underlying writer. Of course, buffering the entire body has a memory overhead, but sometimes there is no way to avoid buffering the whole response, hence the existence of this type. Still, if at all practical, handlers should strive to stream responses by wrapping Write and WriteHeader methods instead of buffering whole response bodies.
Buffering is actually optional. The shouldBuffer function will be called just before the headers are written. If it returns true, the headers and body will be buffered by this recorder and not written to the underlying writer; if false, the headers will be written immediately and the body will be streamed out directly to the underlying writer. If shouldBuffer is nil, the response will never be buffered and will always be streamed directly to the writer.
You can know if shouldBuffer returned true by calling Buffered().
The provided buffer buf should be obtained from a pool for best performance (see the sync.Pool type).
Proper usage of a recorder looks like this:
rec := caddyhttp.NewResponseRecorder(w, buf, shouldBuffer) err := next.ServeHTTP(rec, req) if err != nil { return err } if !rec.Buffered() { return nil } // process the buffered response here
The header map is not buffered; i.e. the ResponseRecorder's Header() method returns the same header map of the underlying ResponseWriter. This is a crucial design decision to allow HTTP trailers to be flushed properly (https://git.sequentialread.com/forest/caddy/issues/3236).
Once you are ready to write the response, there are two ways you can do it. The easier way is to have the recorder do it:
rec.WriteResponse()
This writes the recorded response headers as well as the buffered body. Or, you may wish to do it yourself, especially if you manipulated the buffered body. First you will need to write the headers with the recorded status code, then write the body (this example writes the recorder's body buffer, but you might have your own body to write instead):
w.WriteHeader(rec.Status()) io.Copy(w, rec.Buffer())
type ResponseWriterWrapper ¶
type ResponseWriterWrapper struct {
http.ResponseWriter
}
ResponseWriterWrapper wraps an underlying ResponseWriter and promotes its Pusher/Flusher/Hijacker methods as well. To use this type, embed a pointer to it within your own struct type that implements the http.ResponseWriter interface, then call methods on the embedded value. You can make sure your type wraps correctly by asserting that it implements the HTTPInterfaces interface.
func (*ResponseWriterWrapper) Flush ¶
func (rww *ResponseWriterWrapper) Flush()
Flush implements http.Flusher. It simply calls the underlying ResponseWriter's Flush method if there is one.
func (*ResponseWriterWrapper) Hijack ¶
func (rww *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements http.Hijacker. It simply calls the underlying ResponseWriter's Hijack method if there is one, or returns ErrNotImplemented otherwise.
func (*ResponseWriterWrapper) Push ¶
func (rww *ResponseWriterWrapper) Push(target string, opts *http.PushOptions) error
Push implements http.Pusher. It simply calls the underlying ResponseWriter's Push method if there is one, or returns ErrNotImplemented otherwise.
type Route ¶
type Route struct { // Group is an optional name for a group to which this // route belongs. Grouping a route makes it mutually // exclusive with others in its group; if a route belongs // to a group, only the first matching route in that group // will be executed. Group string `json:"group,omitempty"` // The matcher sets which will be used to qualify this // route for a request (essentially the "if" statement // of this route). Each matcher set is OR'ed, but matchers // within a set are AND'ed together. MatcherSetsRaw RawMatcherSets `json:"match,omitempty" caddy:"namespace=http.matchers"` // The list of handlers for this route. Upon matching a request, they are chained // together in a middleware fashion: requests flow from the first handler to the last // (top of the list to the bottom), with the possibility that any handler could stop // the chain and/or return an error. Responses flow back through the chain (bottom of // the list to the top) as they are written out to the client. // // Not all handlers call the next handler in the chain. For example, the reverse_proxy // handler always sends a request upstream or returns an error. Thus, configuring // handlers after reverse_proxy in the same route is illogical, since they would never // be executed. You will want to put handlers which originate the response at the very // end of your route(s). The documentation for a module should state whether it invokes // the next handler, but sometimes it is common sense. // // Some handlers manipulate the response. Remember that requests flow down the list, and // responses flow up the list. // // For example, if you wanted to use both `templates` and `encode` handlers, you would // need to put `templates` after `encode` in your route, because responses flow up. // Thus, `templates` will be able to parse and execute the plain-text response as a // template, and then return it up to the `encode` handler which will then compress it // into a binary format. // // If `templates` came before `encode`, then `encode` would write a compressed, // binary-encoded response to `templates` which would not be able to parse the response // properly. // // The correct order, then, is this: // // [ // {"handler": "encode"}, // {"handler": "templates"}, // {"handler": "file_server"} // ] // // The request flows ⬇️ DOWN (`encode` -> `templates` -> `file_server`). // // 1. First, `encode` will choose how to `encode` the response and wrap the response. // 2. Then, `templates` will wrap the response with a buffer. // 3. Finally, `file_server` will originate the content from a file. // // The response flows ⬆️ UP (`file_server` -> `templates` -> `encode`): // // 1. First, `file_server` will write the file to the response. // 2. That write will be buffered and then executed by `templates`. // 3. Lastly, the write from `templates` will flow into `encode` which will compress the stream. // // If you think of routes in this way, it will be easy and even fun to solve the puzzle of writing correct routes. HandlersRaw []json.RawMessage `json:"handle,omitempty" caddy:"namespace=http.handlers inline_key=handler"` // If true, no more routes will be executed after this one. Terminal bool `json:"terminal,omitempty"` // decoded values MatcherSets MatcherSets `json:"-"` Handlers []MiddlewareHandler `json:"-"` // contains filtered or unexported fields }
Route consists of a set of rules for matching HTTP requests, a list of handlers to execute, and optional flow control parameters which customize the handling of HTTP requests in a highly flexible and performant manner.
type RouteList ¶
type RouteList []Route
RouteList is a list of server routes that can create a middleware chain.
func (RouteList) Compile ¶
Compile prepares a middleware chain from the route list. This should only be done once: after all the routes have been provisioned, and before serving requests.
func (RouteList) ProvisionHandlers ¶
ProvisionHandlers sets up all the handlers by loading the handler modules. Only call this method directly if you need to set up matchers and handlers separately without having to provision a second time; otherwise use Provision instead.
func (RouteList) ProvisionMatchers ¶
ProvisionMatchers sets up all the matchers by loading the matcher modules. Only call this method directly if you need to set up matchers and handlers separately without having to provision a second time; otherwise use Provision instead.
type Server ¶
type Server struct { // Socket addresses to which to bind listeners. Accepts // [network addresses](/docs/conventions#network-addresses) // that may include port ranges. Listener addresses must // be unique; they cannot be repeated across all defined // servers. Listen []string `json:"listen,omitempty"` // A list of listener wrapper modules, which can modify the behavior // of the base listener. They are applied in the given order. ListenerWrappersRaw []json.RawMessage `json:"listener_wrappers,omitempty" caddy:"namespace=caddy.listeners inline_key=wrapper"` // How long to allow a read from a client's upload. Setting this // to a short, non-zero value can mitigate slowloris attacks, but // may also affect legitimately slow clients. ReadTimeout caddy.Duration `json:"read_timeout,omitempty"` // ReadHeaderTimeout is like ReadTimeout but for request headers. ReadHeaderTimeout caddy.Duration `json:"read_header_timeout,omitempty"` // WriteTimeout is how long to allow a write to a client. Note // that setting this to a small value when serving large files // may negatively affect legitimately slow clients. WriteTimeout caddy.Duration `json:"write_timeout,omitempty"` // IdleTimeout is the maximum time to wait for the next request // when keep-alives are enabled. If zero, a default timeout of // 5m is applied to help avoid resource exhaustion. IdleTimeout caddy.Duration `json:"idle_timeout,omitempty"` // MaxHeaderBytes is the maximum size to parse from a client's // HTTP request headers. MaxHeaderBytes int `json:"max_header_bytes,omitempty"` // Routes describes how this server will handle requests. // Routes are executed sequentially. First a route's matchers // are evaluated, then its grouping. If it matches and has // not been mutually-excluded by its grouping, then its // handlers are executed sequentially. The sequence of invoked // handlers comprises a compiled middleware chain that flows // from each matching route and its handlers to the next. // // By default, all unrouted requests receive a 200 OK response // to indicate the server is working. Routes RouteList `json:"routes,omitempty"` // Errors is how this server will handle errors returned from any // of the handlers in the primary routes. If the primary handler // chain returns an error, the error along with its recommended // status code are bubbled back up to the HTTP server which // executes a separate error route, specified using this property. // The error routes work exactly like the normal routes. Errors *HTTPErrorConfig `json:"errors,omitempty"` // How to handle TLS connections. At least one policy is // required to enable HTTPS on this server if automatic // HTTPS is disabled or does not apply. TLSConnPolicies caddytls.ConnectionPolicies `json:"tls_connection_policies,omitempty"` // AutoHTTPS configures or disables automatic HTTPS within this server. // HTTPS is enabled automatically and by default when qualifying names // are present in a Host matcher and/or when the server is listening // only on the HTTPS port. AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"` // If true, will require that a request's Host header match // the value of the ServerName sent by the client's TLS // ClientHello; often a necessary safeguard when using TLS // client authentication. StrictSNIHost *bool `json:"strict_sni_host,omitempty"` // Enables access logging and configures how access logs are handled // in this server. To minimally enable access logs, simply set this // to a non-null, empty struct. Logs *ServerLogConfig `json:"logs,omitempty"` // Enable experimental HTTP/3 support. Note that HTTP/3 is not a // finished standard and has extremely limited client support. // This field is not subject to compatibility promises. ExperimentalHTTP3 bool `json:"experimental_http3,omitempty"` // Enables H2C ("Cleartext HTTP/2" or "H2 over TCP") support, // which will serve HTTP/2 over plaintext TCP connections if // the client supports it. Because this is not implemented by the // Go standard library, using H2C is incompatible with most // of the other options for this server. Do not enable this // only to achieve maximum client compatibility. In practice, // very few clients implement H2C, and even fewer require it. // This setting applies only to unencrypted HTTP listeners. // ⚠️ Experimental feature; subject to change or removal. AllowH2C bool `json:"allow_h2c,omitempty"` // contains filtered or unexported fields }
Server describes an HTTP server.
type ServerLogConfig ¶
type ServerLogConfig struct { // The default logger name for all logs emitted by this server for // hostnames that are not in the LoggerNames (logger_names) map. DefaultLoggerName string `json:"default_logger_name,omitempty"` // LoggerNames maps request hostnames to a custom logger name. // For example, a mapping of "example.com" to "example" would // cause access logs from requests with a Host of example.com // to be emitted by a logger named "http.log.access.example". LoggerNames map[string]string `json:"logger_names,omitempty"` // By default, all requests to this server will be logged if // access logging is enabled. This field lists the request // hosts for which access logging should be disabled. SkipHosts []string `json:"skip_hosts,omitempty"` // If true, requests to any host not appearing in the // LoggerNames (logger_names) map will not be logged. SkipUnmappedHosts bool `json:"skip_unmapped_hosts,omitempty"` }
ServerLogConfig describes a server's logging configuration. If enabled without customization, all requests to this server are logged to the default logger; logger destinations may be customized per-request-host.
type ShouldBufferFunc ¶
ShouldBufferFunc is a function that returns true if the response should be buffered, given the pending HTTP status code and response headers.
type StaticError ¶
type StaticError struct { // The error message. Optional. Default is no error message. Error string `json:"error,omitempty"` // The recommended HTTP status code. Can be either an integer or a // string if placeholders are needed. Optional. Default is 500. StatusCode WeakString `json:"status_code,omitempty"` }
StaticError implements a simple handler that returns an error. This handler returns an error value, but does not write a response. This is useful when you want the server to act as if an error occurred; for example, to invoke your custom error handling logic.
Since this handler does not write a response, the error information is for use by the server to know how to handle the error.
func (StaticError) CaddyModule ¶
func (StaticError) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (StaticError) ServeHTTP ¶
func (e StaticError) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler) error
func (*StaticError) UnmarshalCaddyfile ¶
func (e *StaticError) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:
error [<matcher>] <status>|<message> [<status>] { message <text> }
If there is just one argument (other than the matcher), it is considered to be a status code if it's a valid positive integer of 3 digits.
type StaticResponse ¶
type StaticResponse struct { // The HTTP status code to respond with. Can be an integer or, // if needing to use a placeholder, a string. StatusCode WeakString `json:"status_code,omitempty"` // Header fields to set on the response. Headers http.Header `json:"headers,omitempty"` // The response body. Body string `json:"body,omitempty"` // If true, the server will close the client's connection // after writing the response. Close bool `json:"close,omitempty"` // Immediately and forcefully closes the connection without // writing a response. Interrupts any other HTTP streams on // the same connection. Abort bool `json:"abort,omitempty"` }
StaticResponse implements a simple responder for static responses.
func (StaticResponse) CaddyModule ¶
func (StaticResponse) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (StaticResponse) ServeHTTP ¶
func (s StaticResponse) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler) error
func (*StaticResponse) UnmarshalCaddyfile ¶
func (s *StaticResponse) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:
respond [<matcher>] <status>|<body> [<status>] { body <text> close }
If there is just one argument (other than the matcher), it is considered to be a status code if it's a valid positive integer of 3 digits.
type Subroute ¶
type Subroute struct { // The primary list of routes to compile and execute. Routes RouteList `json:"routes,omitempty"` // If the primary routes return an error, error handling // can be promoted to this configuration instead. Errors *HTTPErrorConfig `json:"errors,omitempty"` }
Subroute implements a handler that compiles and executes routes. This is useful for a batch of routes that all inherit the same matchers, or for multiple routes that should be treated as a single route.
You can also use subroutes to handle errors from its handlers. First the primary routes will be executed, and if they return an error, the errors routes will be executed; in that case, an error is only returned to the entry point at the server if there is an additional error returned from the errors routes.
func (Subroute) CaddyModule ¶
func (Subroute) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
type VarsMatcher ¶
VarsMatcher is an HTTP request matcher which can match requests based on variables in the context.
func (VarsMatcher) CaddyModule ¶
func (VarsMatcher) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (VarsMatcher) Match ¶
func (m VarsMatcher) Match(r *http.Request) bool
Match matches a request based on variables in the context.
func (*VarsMatcher) UnmarshalCaddyfile ¶
func (m *VarsMatcher) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type VarsMiddleware ¶
VarsMiddleware is an HTTP middleware which sets variables in the context, mainly for use by placeholders. The placeholders have the form: `{http.vars.variable_name}`
func (VarsMiddleware) CaddyModule ¶
func (VarsMiddleware) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (VarsMiddleware) ServeHTTP ¶
func (t VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error
type WeakString ¶
type WeakString string
WeakString is a type that unmarshals any JSON value as a string literal, with the following exceptions:
1. actual string values are decoded as strings; and 2. null is decoded as empty string;
and provides methods for getting the value as various primitive types. However, using this type removes any type safety as far as deserializing JSON is concerned.
func (WeakString) Bool ¶
func (ws WeakString) Bool() bool
Bool returns ws as a boolean. If ws is not a boolean, false is returned.
func (WeakString) Float64 ¶
func (ws WeakString) Float64() float64
Float64 returns ws as a float64. If ws is not a float value, the zero value is returned.
func (WeakString) Int ¶
func (ws WeakString) Int() int
Int returns ws as an integer. If ws is not an integer, 0 is returned.
func (WeakString) MarshalJSON ¶
func (ws WeakString) MarshalJSON() ([]byte, error)
MarshalJSON marshals was a boolean if true or false, a number if an integer, or a string otherwise.
func (*WeakString) UnmarshalJSON ¶
func (ws *WeakString) UnmarshalJSON(b []byte) error
UnmarshalJSON satisfies json.Unmarshaler according to this type's documentation.