Documentation ¶
Index ¶
- Constants
- Variables
- func CopyHeader(dest, src http.Header)
- 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 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 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 ( // CommonLogFormat is the common log format. https://en.wikipedia.org/wiki/Common_Log_Format CommonLogFormat = `{http.request.remote.host} ` + CommonLogEmptyValue + ` {http.authentication.user.id} [{time.now.common_log}] "{http.request.orig_method} {http.request.orig_uri} {http.request.proto}" {http.response.status} {http.response.size}` // CommonLogEmptyValue is the common empty log value. CommonLogEmptyValue = "-" )
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 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 CopyHeader ¶
CopyHeader copies HTTP headers by completely replacing dest with src. (This allows deletions to be propagated, assuming src started as a consistent copy of dest.)
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, flexible HTTP server 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. 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: // // {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} // A short, human-conveyable ID for 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 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 (case-insensitive).
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 caddy.ModuleMap `json:"-" caddy:"namespace=http.matchers"` 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 (case-insensitive).
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) 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.
func (MatcherSets) AnyMatch ¶
func (ms MatcherSets) AnyMatch(req *http.Request) bool
AnyMatch returns true if req matches any of the matcher sets in mss 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 ¶
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 []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 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 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
After a response has been buffered, remember that any upstream header manipulations are only manifest in the recorder's Header(), not the Header() of the underlying ResponseWriter. Thus if you wish to inspect or change response headers, you either need to use rec.Header(), or copy rec.Header() into w.Header() first (see caddyhttp.CopyHeader).
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 copy the recorded headers, then 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):
caddyhttp.CopyHeader(w.Header(), rec.Header()) 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. If a route belongs to a group, only // the first matching route in the group will be used. 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, even if they matched. Terminal bool `json:"terminal,omitempty"` // decoded values MatcherSets MatcherSets `json:"-"` Handlers []MiddlewareHandler `json:"-"` }
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) BuildCompositeRoute ¶
BuildCompositeRoute creates a chain of handlers by applying all of the matching routes.
type Server ¶
type Server struct { // Socket interfaces to which to bind listeners. Caddy network // addresses have the following form: // // network/address // // The network part is anything that [Go's `net` package](https://golang.org/pkg/net/) // recognizes, and is optional. The default network is `tcp`. If // a network is specified, a single forward slash `/` is used to // separate the network and address portions. // // The address part may be any of these forms: // // - `host` // - `host:port` // - `:port` // - `/path/to/unix/socket` // // The host may be any hostname, resolvable domain name, or IP address. // The port may be a single value (`:8080`) or a range (`:8080-8085`). // A port range will be multiplied into singular addresses. Not all // config parameters accept port ranges, but Listen does. // // Valid examples: // // :8080 // 127.0.0.1:8080 // localhost:8080 // localhost:8080-8085 // tcp/localhost:8080 // tcp/localhost:8080-8085 // udp/localhost:9005 // unix//path/to/socket // Listen []string `json:"listen,omitempty"` // 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, ReadTimeout is used. // If both are zero, there is no timeout. 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. // When a request comes in, each route's matchers will // be evaluated against the request, and matching routes // will be compiled into a middleware chain in the order // in which they appear in the list. 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. 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. AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"` // MaxRehandles is the maximum number of times to allow a // request to be rehandled, to prevent accidental infinite // loops. Default: 1. MaxRehandles *int `json:"max_rehandles,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"` // Logs customizes how access logs are handled in this server. 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"` // contains filtered or unexported fields }
Server describes an HTTP server.
type ServerLogConfig ¶
type ServerLogConfig struct { // 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"` }
ServerLogConfig describes a server's logging configuration.
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 recommended HTTP status code. Can be either an integer or a // string if placeholders are needed. Optional. Default is 500. Error string `json:"error,omitempty"` // The error message. Optional. Default is no error message. 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
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"` }
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 { // 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 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).
You can also use subroutes to handle errors from specific 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.
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package encode implements an encoder middleware for Caddy.
|
Package encode implements an encoder middleware for Caddy. |