Documentation ¶
Index ¶
- Constants
- Variables
- func StatusCodeMatches(actual, configured int) bool
- type App
- type AutoHTTPSConfig
- type HTTPErrorConfig
- type HTTPInterfaces
- type Handler
- type HandlerError
- type HandlerFunc
- type MatchHeader
- type MatchHeaderRE
- type MatchHost
- type MatchMethod
- type MatchNegate
- func (MatchNegate) CaddyModule() caddy.ModuleInfo
- func (m MatchNegate) MarshalJSON() ([]byte, error)
- func (m MatchNegate) Match(r *http.Request) bool
- func (m *MatchNegate) Provision(ctx caddy.Context) error
- func (m *MatchNegate) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- func (m *MatchNegate) UnmarshalJSON(data []byte) error
- type MatchPath
- type MatchPathRE
- type MatchProtocol
- type MatchQuery
- type MatchRegexp
- type MatchRemoteIP
- type MatchStarlarkExpr
- type MatchTable
- type MatcherSet
- type MatcherSets
- type Middleware
- type MiddlewareHandler
- type RawMatcherSets
- type RequestMatcher
- type ResponseMatcher
- type ResponseRecorder
- type ResponseWriterWrapper
- type Route
- type RouteList
- type Server
- 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 VarCtxKey caddy.CtxKey = "vars" // For the unmodified URL that originally came in with a request OriginalURLCtxKey caddy.CtxKey = "original_url" )
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 DefaultMaxRehandles = 3
DefaultMaxRehandles is the maximum number of rehandles to allow, if not specified explicitly.
var ErrNotImplemented = fmt.Errorf("method not implemented")
ErrNotImplemented is returned when an underlying ResponseWriter does not implement the required method.
var ErrRehandle = fmt.Errorf("rehandling request")
ErrRehandle is a special error value that Handlers should return from their ServeHTTP() method if the request is to be re-processed. This error value is a sentinel value that should not be wrapped or modified.
Functions ¶
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 int `json:"http_port,omitempty"` HTTPSPort int `json:"https_port,omitempty"` GracePeriod caddy.Duration `json:"grace_period,omitempty"` Servers map[string]*Server `json:"servers,omitempty"` // contains filtered or unexported fields }
App is the HTTP app for Caddy.
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.
type HTTPErrorConfig ¶
type HTTPErrorConfig struct {
Routes RouteList `json:"routes,omitempty"`
}
HTTPErrorConfig determines how to handle errors from the HTTP handlers.
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 Message string // an optional message that can be shown to the user Recommendations []string // an optional list of things to try to resolve the 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 MatchHeader ¶
MatchHeader matches requests by header fields.
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.
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.
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 MatchNegate ¶
type MatchNegate struct { MatchersRaw map[string]json.RawMessage `json:"-"` Matchers MatcherSet `json:"-"` }
MatchNegate matches requests by negating its matchers' results.
func (MatchNegate) CaddyModule ¶
func (MatchNegate) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (MatchNegate) MarshalJSON ¶
func (m MatchNegate) MarshalJSON() ([]byte, error)
MarshalJSON marshals m's matchers.
func (MatchNegate) Match ¶
func (m MatchNegate) Match(r *http.Request) bool
Match returns true if r matches m. Since this matcher negates the embedded matchers, false is returned if any of its matchers match.
func (*MatchNegate) Provision ¶
func (m *MatchNegate) Provision(ctx caddy.Context) error
Provision loads the matcher modules to be negated.
func (*MatchNegate) UnmarshalCaddyfile ¶
func (m *MatchNegate) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (*MatchNegate) UnmarshalJSON ¶
func (m *MatchNegate) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshals data into m's unexported map field. This is done because we cannot embed the map directly into the struct, but we need a struct because we need another field just for the provisioned modules.
type MatchPath ¶
type MatchPath []string
MatchPath matches requests by the URI's path.
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.
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.
func (*MatchQuery) UnmarshalCaddyfile ¶
func (m *MatchQuery) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile implements caddyfile.Unmarshaler.
type MatchRegexp ¶
type MatchRegexp struct { Name string `json:"name,omitempty"` Pattern string `json:"pattern"` // contains filtered or unexported fields }
MatchRegexp is an embeddable type for matching using regular expressions.
func (*MatchRegexp) Match ¶
func (mre *MatchRegexp) Match(input string, repl caddy.Replacer, scope string) 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). Capture groups stored to repl will take on the name "http.matchers.<scope>.<mre.Name>.<N>" where <N> is the name or number of the capture group.
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 { Ranges []string `json:"ranges,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 MatchStarlarkExpr ¶
type MatchStarlarkExpr string
MatchStarlarkExpr matches requests by evaluating a Starlark expression.
func (MatchStarlarkExpr) CaddyModule ¶
func (MatchStarlarkExpr) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
type MatchTable ¶
type MatchTable string // TODO: finish implementing
MatchTable matches requests by values in the table.
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.
type Middleware ¶
type Middleware func(HandlerFunc) HandlerFunc
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 []map[string]json.RawMessage
RawMatcherSets is a group of matcher sets in their raw, JSON form.
func (RawMatcherSets) Setup ¶
func (rm RawMatcherSets) Setup(ctx caddy.Context) (MatcherSets, error)
Setup sets up all matcher sets by loading each matcher module and returning the group of provisioned matcher sets.
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 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. Headers http.Header `json:"headers,omitempty"` }
ResponseMatcher is a type which can determine if a given response status code and its headers match some criteria.
type ResponseRecorder ¶
type ResponseRecorder interface { HTTPInterfaces Status() int Buffer() *bytes.Buffer Buffered() bool Size() int }
ResponseRecorder is a http.ResponseWriter that records responses instead of writing them to the client.
func NewResponseRecorder ¶
func NewResponseRecorder(w http.ResponseWriter, buf *bytes.Buffer, shouldBuffer func(status int) bool) ResponseRecorder
NewResponseRecorder returns a new ResponseRecorder that can be used instead of a real http.ResponseWriter. The recorder is useful for middlewares which need to buffer a responder's response and process it in its entirety before actually allowing the response to be written. Of course, this has a performance overhead, but sometimes there is no way to avoid buffering the whole response. Still, if at all practical, middlewares should strive to stream responses by wrapping Write and WriteHeader methods instead of buffering whole response bodies.
Recorders optionally buffer the response. When the headers are to be written, shouldBuffer will be called with the status code that is being written. The rest of the headers can be read from w.Header(). If shouldBuffer returns true, the response will be buffered. You can know the response was buffered if the Buffered() method returns true. If the response was not buffered, Buffered() will return false and that means the response bypassed the recorder and was written directly to the underlying writer. If shouldBuffer is nil, the response will never be buffered (it will always be streamed directly), and buf can also safely be nil.
Before calling this function in a middleware handler, make a new buffer or obtain one from a pool (use the sync.Pool) type. Using a pool is generally recommended for performance gains; do profiling to ensure this is the case. If using a pool, be sure to reset the buffer before using it.
The returned recorder can be used in place of w when calling the next handler in the chain. When that handler returns, you can read the status code from the recorder's Status() method. The response body fills buf if it was buffered, and the headers are available via w.Header().
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 string `json:"group,omitempty"` MatcherSetsRaw RawMatcherSets `json:"match,omitempty"` HandlersRaw []json.RawMessage `json:"handle,omitempty"` Terminal bool `json:"terminal,omitempty"` // decoded values MatcherSets MatcherSets `json:"-"` Handlers []MiddlewareHandler `json:"-"` }
Route represents a set of matching rules, middlewares, and a responder for handling HTTP requests.
type RouteList ¶
type RouteList []Route
RouteList is a list of server routes that can create a middleware chain.
func (RouteList) BuildCompositeRoute ¶
BuildCompositeRoute creates a chain of handlers by applying all of the matching routes.
type Server ¶
type Server struct { Listen []string `json:"listen,omitempty"` ReadTimeout caddy.Duration `json:"read_timeout,omitempty"` ReadHeaderTimeout caddy.Duration `json:"read_header_timeout,omitempty"` WriteTimeout caddy.Duration `json:"write_timeout,omitempty"` IdleTimeout caddy.Duration `json:"idle_timeout,omitempty"` MaxHeaderBytes int `json:"max_header_bytes,omitempty"` Routes RouteList `json:"routes,omitempty"` Errors *HTTPErrorConfig `json:"errors,omitempty"` TLSConnPolicies caddytls.ConnectionPolicies `json:"tls_connection_policies,omitempty"` AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"` MaxRehandles *int `json:"max_rehandles,omitempty"` StrictSNIHost *bool `json:"strict_sni_host,omitempty"` // This field is not subject to compatibility promises ExperimentalHTTP3 bool `json:"experimental_http3,omitempty"` // contains filtered or unexported fields }
Server is an HTTP server.
type StaticError ¶
type StaticError struct { Error string `json:"error,omitempty"` StatusCode WeakString `json:"status_code,omitempty"` }
StaticError implements a simple handler that returns an 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
type StaticResponse ¶
type StaticResponse struct { StatusCode WeakString `json:"status_code,omitempty"` Headers http.Header `json:"headers,omitempty"` Body string `json:"body,omitempty"` Close bool `json:"close,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 <text> close }
type Subroute ¶
type Subroute struct {
Routes RouteList `json:"routes,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 routes with matchers that must be have deferred evaluation (e.g. if they depend on placeholders created by other matchers that need to be evaluated first).
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.
type VarsMiddleware ¶
VarsMiddleware is an HTTP middleware which sets variables in the context, mainly for use by placeholders.
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package encode implements an encoder middleware for Caddy.
|
Package encode implements an encoder middleware for Caddy. |