caddy: Index | Files

package httpserver

import ""

Package httpserver implements an HTTP server on top of Caddy.


Package Files

condition.go error.go https.go logger.go middleware.go mitm.go path.go plugin.go recorder.go replacer.go responsewriterwrapper.go roller.go server.go siteconfig.go tplcontext.go vhosttrie.go


const (
    // ReplacerCtxKey is the context key for a per-request replacer.
    ReplacerCtxKey caddy.CtxKey = "replacer"

    // RemoteUserCtxKey is the key for the remote user of the request, if any (basicauth).
    RemoteUserCtxKey caddy.CtxKey = "remote_user"

    // MitmCtxKey is the key for the result of MITM detection
    MitmCtxKey caddy.CtxKey = "mitm"

    // RequestIDCtxKey is the key for the U4 UUID value
    RequestIDCtxKey caddy.CtxKey = "request_id"

Context key constants.

const (

    // cipher suites missing from the crypto/tls package,
    // in no particular order here
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xc024
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   = 0xc028
    TLS_RSA_WITH_AES_256_CBC_SHA256         = 0x3d
    TLS_DHE_RSA_WITH_AES_128_CBC_SHA        = 0x33
    TLS_DHE_RSA_WITH_AES_256_CBC_SHA        = 0x39
    TLS_RSA_WITH_RC4_128_MD5                = 0x4

    // new PSK ciphers introduced by TLS 1.3, not (yet) in crypto/tls
    TLS_AES_128_GCM_SHA256       = 0x1301
    TLS_AES_256_GCM_SHA384       = 0x1302
    TLS_CHACHA20_POLY1305_SHA256 = 0x1303
    TLS_AES_128_CCM_SHA256       = 0x1304
    TLS_AES_128_CCM_8_SHA256     = 0x1305

Define variables used for TLS communication

const (
    // DefaultHost is the default host.
    DefaultHost = ""
    // DefaultPort is the default port.
    DefaultPort = "2015"
    // DefaultRoot is the default root folder.
    DefaultRoot = "."
    // DefaultHTTPPort is the default port for HTTP.
    DefaultHTTPPort = "80"
    // DefaultHTTPSPort is the default port for HTTPS.
    DefaultHTTPSPort = "443"
const (

    // MaxLogBodySize limits the size of logged request's body
    MaxLogBodySize = 100 * 1024
const OriginalURLCtxKey = caddy.CtxKey("original_url")

OriginalURLCtxKey is the key for accessing the original, incoming URL on an HTTP request.


var (
    // Root is the site root
    Root = DefaultRoot

    // Host is the site host
    Host = DefaultHost

    // Port is the site port
    Port = DefaultPort

    // GracefulTimeout is the maximum duration of a graceful shutdown.
    GracefulTimeout time.Duration

    // HTTP2 indicates whether HTTP2 is enabled or not.
    HTTP2 bool

    // QUIC indicates whether QUIC is enabled or not.
    QUIC bool

These "soft defaults" are configurable by command line flags, etc.

var CaseSensitivePath = false

CaseSensitivePath determines if paths should be case sensitive. This is configurable via CASE_SENSITIVE_PATH environment variable.

var EmptyNext = HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { return 0, nil })

EmptyNext is a no-op function that can be passed into Middleware functions so that the assignment to the Next field of the Handler can be tested.

Used primarily for testing but needs to be exported so plugins can use this as a convenience.

var ErrMaxBytesExceeded = errors.New("http: request body too large")

ErrMaxBytesExceeded is the error returned by MaxBytesReader when the request body exceeds the limit imposed

var TemplateFuncs = template.FuncMap{}

TemplateFuncs contains user-defined functions for execution in templates.

func ContextInclude Uses

func ContextInclude(filename string, ctx interface{}, fs http.FileSystem) (string, error)

ContextInclude opens filename using fs and executes a template with the context ctx. This does the same thing that Context.Include() does, but with the ability to provide your own context so that the included files can have access to additional fields your type may provide. You can embed Context in your type, then override its Include method to call this function with ctx being the instance of your type, and fs being Context.Root.

func DefaultErrorFunc Uses

func DefaultErrorFunc(w http.ResponseWriter, r *http.Request, status int)

DefaultErrorFunc responds to an HTTP request with a simple description of the specified HTTP status code.

func IfMatcherKeyword Uses

func IfMatcherKeyword(c *caddy.Controller) bool

IfMatcherKeyword checks if the next value in the dispenser is a keyword for 'if' config block. If true, remaining arguments in the dispenser are cleared to keep the dispenser valid for use.

func IndexFile Uses

func IndexFile(root http.FileSystem, fpath string, indexFiles []string) (string, bool)

IndexFile looks for a file in /root/fpath/indexFile for each string in indexFiles. If an index file is found, it returns the root-relative path to the file and true. If no index file is found, empty string and false is returned. fpath must end in a forward slash '/' otherwise no index files will be tried (directory paths must end in a forward slash according to HTTP).

All paths passed into and returned from this function use '/' as the path separator, just like URLs. IndexFle handles path manipulation internally for systems that use different path separators.

func IsLogRollerSubdirective Uses

func IsLogRollerSubdirective(subdir string) bool

IsLogRollerSubdirective is true if the subdirective is for the log roller.

func ParseRoller Uses

func ParseRoller(l *LogRoller, what string, where ...string) error

ParseRoller parses roller contents out of c.

func RegisterDevDirective Uses

func RegisterDevDirective(name, before string)

RegisterDevDirective splices name into the list of directives immediately before another directive. This function is ONLY for plugin development purposes! NEVER use it for a plugin that you are not currently building. If before is empty, the directive will be appended to the end of the list.

It is imperative that directives execute in the proper order, and hard-coding the list of directives guarantees a correct, absolute order every time. This function is convenient when developing a plugin, but it does not guarantee absolute ordering. Multiple plugins registering directives with this function will lead to non- deterministic builds and buggy software.

Directive names must be lower-cased and unique. Any errors here are fatal, and even successful calls print a message to stdout as a reminder to use it only in development.

func SafePath Uses

func SafePath(siteRoot, reqPath string) string

SafePath joins siteRoot and reqPath and converts it to a path that can be used to access a path on the local disk. It ensures the path does not traverse outside of the site root.

If opening a file, use http.Dir instead.

func SameNext Uses

func SameNext(next1, next2 Handler) bool

SameNext does a pointer comparison between next1 and next2.

Used primarily for testing but needs to be exported so plugins can use this as a convenience.

func SetLastModifiedHeader Uses

func SetLastModifiedHeader(w http.ResponseWriter, modTime time.Time)

SetLastModifiedHeader checks if the provided modTime is valid and if it is sets it as a Last-Modified header to the ResponseWriter. If the modTime is in the future the current time is used instead.

func WriteSiteNotFound Uses

func WriteSiteNotFound(w http.ResponseWriter, r *http.Request)

WriteSiteNotFound writes appropriate error code to w, signaling that requested host is not served by Caddy on a given port.

func WriteTextResponse Uses

func WriteTextResponse(w http.ResponseWriter, status int, body string)

WriteTextResponse writes body with code status to w. The body will be interpreted as plain text.

type Address Uses

type Address struct {
    Original, Scheme, Host, Port, Path string

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

The Host field must be in a normalized form.

func (Address) Key Uses

func (a Address) Key() string

Key is similar to String, just replaces scheme and host values with modified values. Unlike String it doesn't add anything default (scheme, port, etc)

func (Address) Normalize Uses

func (a Address) Normalize() Address

Normalize normalizes URL: turn scheme and host names into lower case

func (Address) String Uses

func (a Address) String() string

String returns a human-friendly print of the address.

func (Address) VHost Uses

func (a Address) VHost() string

VHost returns a sensible concatenation of Host:Port/Path from a. It's basically the a.Original but without the scheme.

type ConfigSelector Uses

type ConfigSelector []HandlerConfig

ConfigSelector selects a configuration.

func (ConfigSelector) Select Uses

func (c ConfigSelector) Select(r *http.Request) (config HandlerConfig)

Select selects a Config. This chooses the config with the longest length.

type Context Uses

type Context struct {
    Root http.FileSystem
    Req  *http.Request
    URL  *url.URL
    Args []interface{} // defined by arguments to .Include
    // contains filtered or unexported fields

Context is the context with which Caddy templates are executed.

func NewContextWithHeader Uses

func NewContextWithHeader(rh http.Header) Context

NewContextWithHeader creates a context with given response header.

To plugin developer: The returned context's exported fileds remain empty, you should then initialize them if you want.

func (c Context) AddLink(link string) string

AddLink adds a link header in response see

func (Context) Cookie Uses

func (c Context) Cookie(name string) string

Cookie gets the value of a cookie with name name.

func (Context) Env Uses

func (c Context) Env() map[string]string

Env gets a map of the environment variables.

func (Context) Ext Uses

func (c Context) Ext(pathStr string) string

Ext returns the suffix beginning at the final dot in the final slash-separated element of the pathStr (or in other words, the file extension).

func (Context) Files Uses

func (c Context) Files(name string) ([]string, error)

Files reads and returns a slice of names from the given directory relative to the root of Context c.

func (Context) Header Uses

func (c Context) Header(name string) string

Header gets the value of a request header with field name.

func (Context) Host Uses

func (c Context) Host() (string, error)

Host returns the hostname portion of the Host header from the HTTP request.

func (Context) Hostname Uses

func (c Context) Hostname() string

Hostname gets the (remote) hostname of the client making the request.

func (Context) IP Uses

func (c Context) IP() string

IP gets the (remote) IP address of the client making the request.

func (Context) Include Uses

func (c Context) Include(filename string, args ...interface{}) (string, error)

Include returns the contents of filename relative to the site root.

func (Context) IsMITM Uses

func (c Context) IsMITM() bool

IsMITM returns true if it seems likely that the TLS connection is being intercepted.

func (Context) Join Uses

func (c Context) Join(a []string, sep string) string

Join is a pass-through to strings.Join. It will join the first argument slice with the separator in the second argument and return the result.

func (Context) Map Uses

func (c Context) Map(values ...interface{}) (map[string]interface{}, error)

Map will convert the arguments into a map. It expects alternating string keys and values. This is useful for building more complicated data structures if you are using subtemplates or things like that.

func (Context) Markdown Uses

func (c Context) Markdown(filename string) (string, error)

Markdown returns the HTML contents of the markdown contained in filename (relative to the site root).

func (Context) Method Uses

func (c Context) Method() string

Method returns the method (GET, POST, etc.) of the request.

func (Context) Now Uses

func (c Context) Now(format string) string

Now returns the current timestamp in the specified format.

func (Context) NowDate Uses

func (c Context) NowDate() time.Time

NowDate returns the current date/time that can be used in other time functions.

func (Context) PathMatches Uses

func (c Context) PathMatches(pattern string) bool

PathMatches returns true if the path portion of the request URL matches pattern.

func (Context) Port Uses

func (c Context) Port() (string, error)

Port returns the port portion of the Host header if specified.

func (Context) RandomString Uses

func (c Context) RandomString(minLen, maxLen int) string

RandomString generates a random string of random length given length bounds. Thanks to for the clever technique that is fairly fast, secure, and maintains proper distributions over the dictionary.

func (Context) Replace Uses

func (c Context) Replace(input, find, replacement string) string

Replace replaces instances of find in input with replacement.

func (Context) ServerIP Uses

func (c Context) ServerIP() string

ServerIP gets the (local) IP address of the server. TODO: The bind directive should be honored in this method (see PR #1474).

func (Context) Slice Uses

func (c Context) Slice(elems ...interface{}) []interface{}

Slice will convert the given arguments into a slice.

func (Context) Split Uses

func (c Context) Split(s string, sep string) []string

Split is a pass-through to strings.Split. It will split the first argument at each instance of the separator and return a slice of strings.

func (Context) StripExt Uses

func (c Context) StripExt(path string) string

StripExt returns the input string without the extension, which is the suffix starting with the final '.' character but not before the final path separator ('/') character. If there is no extension, the whole input is returned.

func (Context) StripHTML Uses

func (c Context) StripHTML(s string) string

StripHTML returns s without HTML tags. It is fairly naive but works with most valid HTML inputs.

func (Context) TLSVersion Uses

func (c Context) TLSVersion() (ret string)

Returns either TLS protocol version if TLS used or empty string otherwise

func (Context) ToLower Uses

func (c Context) ToLower(s string) string

ToLower will convert the given string to lower case.

func (Context) ToUpper Uses

func (c Context) ToUpper(s string) string

ToUpper will convert the given string to upper case.

func (Context) Truncate Uses

func (c Context) Truncate(input string, length int) string

Truncate truncates the input string to the given length. If length is negative, it returns that many characters starting from the end of the string. If the absolute value of length is greater than len(input), the whole input is returned.

func (Context) URI Uses

func (c Context) URI() string

URI returns the raw, unprocessed request URI (including query string and hash) obtained directly from the Request-Line of the HTTP request.

type HTTPInterfaces Uses

type HTTPInterfaces interface {

HTTPInterfaces mix all the interfaces that middleware ResponseWriters need to support.

type Handler Uses

type Handler interface {
    ServeHTTP(http.ResponseWriter, *http.Request) (int, error)

Handler is like http.Handler except ServeHTTP may return a status code and/or error.

If ServeHTTP writes the response header, it should return a status code of 0. This signals to other handlers before it that the response is already handled, and that they should not write to it also. Keep in mind that writing to the response body writes the header, too.

If ServeHTTP encounters an error, it should return the error value so it can be logged by designated error-handling middleware.

If writing a response after calling the next ServeHTTP method, the returned status code SHOULD be used when writing the response.

If handling errors after calling the next ServeHTTP method, the returned error value SHOULD be logged or handled accordingly.

Otherwise, return values should be propagated down the middleware chain by returning them unchanged.

type HandlerConfig Uses

type HandlerConfig interface {
    BasePath() string

HandlerConfig is a middleware configuration. This makes it possible for middlewares to have a common configuration interface.

TODO The long term plan is to get all middleware implement this interface for configurations.

type HandlerFunc Uses

type HandlerFunc func(http.ResponseWriter, *http.Request) (int, error)

HandlerFunc is a convenience type like http.HandlerFunc, except ServeHTTP returns a status code and an error. See Handler documentation for more information.

func (HandlerFunc) ServeHTTP Uses

func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)

ServeHTTP implements the Handler interface.

type IfMatcher Uses

type IfMatcher struct {
    Enabled bool // if true, matcher has been configured; otherwise it's no-op
    // contains filtered or unexported fields

IfMatcher is a RequestMatcher for 'if' conditions.

func (IfMatcher) And Uses

func (m IfMatcher) And(r *http.Request) bool

And returns true if all conditions in m are true.

func (IfMatcher) Match Uses

func (m IfMatcher) Match(r *http.Request) bool

Match satisfies RequestMatcher interface. It returns true if the conditions in m are true.

func (IfMatcher) Or Uses

func (m IfMatcher) Or(r *http.Request) bool

Or returns true if any of the conditions in m is true.

type Limits Uses

type Limits struct {
    MaxRequestHeaderSize int64
    MaxRequestBodySizes  []PathLimit

Limits specify size limit of request's header and body.

type ListenerMiddleware Uses

type ListenerMiddleware func(caddy.Listener) caddy.Listener

ListenerMiddleware is similar to the Middleware type, except it chains one net.Listener to the next.

type LogRoller Uses

type LogRoller struct {
    Disabled   bool
    Filename   string
    MaxSize    int
    MaxAge     int
    MaxBackups int
    Compress   bool
    LocalTime  bool

LogRoller implements a type that provides a rolling logger.

func DefaultLogRoller Uses

func DefaultLogRoller() *LogRoller

DefaultLogRoller will roll logs by default.

func (LogRoller) GetLogWriter Uses

func (l LogRoller) GetLogWriter() io.Writer

GetLogWriter returns an io.Writer that writes to a rolling logger. This should be called only from the main goroutine (like during server setup) because this method is not thread-safe; it is careful to create only one log writer per log file, even if the log file is shared by different sites or middlewares. This ensures that rolling is synchronized, since a process (or multiple processes) should not create more than one roller on the same file at the same time. See issue #1363.

type Logger Uses

type Logger struct {
    Output string
    Roller *LogRoller

    V4ipMask     net.IPMask
    V6ipMask     net.IPMask
    IPMaskExists bool
    Exceptions   []string
    // contains filtered or unexported fields

Logger is shared between errors and log plugins and supports both logging to a file (with an optional file roller), local and remote syslog servers.

func NewTestLogger Uses

func NewTestLogger(buffer *bytes.Buffer) *Logger

NewTestLogger creates logger suitable for testing purposes

func (*Logger) Attach Uses

func (l *Logger) Attach(controller *caddy.Controller)

Attach binds logger Start and Close functions to controller's OnStartup and OnShutdown hooks.

func (*Logger) Close Uses

func (l *Logger) Close() error

Close closes open log files or connections to syslog.

func (Logger) MaskIP Uses

func (l Logger) MaskIP(ip string) string

func (Logger) Printf Uses

func (l Logger) Printf(format string, args ...interface{})

Printf wraps underlying logger with mutex

func (Logger) Println Uses

func (l Logger) Println(args ...interface{})

Println wraps underlying logger with mutex

func (Logger) ShouldLog Uses

func (l Logger) ShouldLog(path string) bool

ShouldLog returns true if the path is not exempted from being logged (i.e. it is not found in l.Exceptions).

func (*Logger) Start Uses

func (l *Logger) Start() error

Start initializes logger opening files or local/remote syslog connections

type Middleware Uses

type Middleware func(Handler) Handler

Middleware is the middle layer which represents the traditional idea of middleware: it chains one Handler to the next by being passed the next Handler in the chain.

type NonCloseNotifierError Uses

type NonCloseNotifierError struct {
    // underlying type which doesn't implement CloseNotify
    Underlying interface{}

NonCloseNotifierError is more descriptive error caused by a non closeNotifier

func (NonCloseNotifierError) Error Uses

func (c NonCloseNotifierError) Error() string

Implement Error

type NonFlusherError Uses

type NonFlusherError struct {
    // underlying type which doesn't implement Flush
    Underlying interface{}

NonFlusherError is more descriptive error caused by a non flusher

func (NonFlusherError) Error Uses

func (f NonFlusherError) Error() string

Implement Error

type NonHijackerError Uses

type NonHijackerError struct {
    // underlying type which doesn't implement Hijack
    Underlying interface{}

NonHijackerError is more descriptive error caused by a non hijacker

func (NonHijackerError) Error Uses

func (h NonHijackerError) Error() string

Implement Error

type NonPusherError Uses

type NonPusherError struct {
    // underlying type which doesn't implement pusher
    Underlying interface{}

NonPusherError is more descriptive error caused by a non pusher

func (NonPusherError) Error Uses

func (c NonPusherError) Error() string

Implement Error

type Path Uses

type Path string

Path represents a URI path. It should usually be set to the value of a request path.

func (Path) Matches Uses

func (p Path) Matches(base string) bool

Matches checks to see if base matches p. The correct usage of this method sets p as the request path, and base as a Caddyfile (user-defined) rule path.

Path matching will probably not always be a direct comparison; this method assures that paths can be easily and consistently matched.

Multiple slashes are collapsed/merged. See issue #1859.

type PathLimit Uses

type PathLimit struct {
    Path  string
    Limit int64

PathLimit is a mapping from a site's path to its corresponding maximum request body size (in bytes)

type PathMatcher Uses

type PathMatcher string

PathMatcher is a Path RequestMatcher.

func (PathMatcher) Match Uses

func (p PathMatcher) Match(r *http.Request) bool

Match satisfies RequestMatcher.

type Replacer Uses

type Replacer interface {
    Replace(string) string
    Set(key, value string)

Replacer is a type which can replace placeholder substrings in a string with actual values from a http.Request and ResponseRecorder. Always use NewReplacer to get one of these. Any placeholders made with Set() should overwrite existing values if the key is already used.

func NewReplacer Uses

func NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Replacer

NewReplacer makes a new replacer based on r and rr which are used for request and response placeholders, respectively. Request placeholders are created immediately, whereas response placeholders are not created until Replace() is invoked. rr may be nil if it is not available. emptyValue should be the string that is used in place of empty string (can still be empty string).

type RequestMatcher Uses

type RequestMatcher interface {
    Match(r *http.Request) bool

RequestMatcher checks to see if current request should be handled by underlying handler.

func MergeRequestMatchers Uses

func MergeRequestMatchers(matchers ...RequestMatcher) RequestMatcher

MergeRequestMatchers merges multiple RequestMatchers into one. This allows a middleware to use multiple RequestMatchers.

func SetupIfMatcher Uses

func SetupIfMatcher(controller *caddy.Controller) (RequestMatcher, error)

SetupIfMatcher parses `if` or `if_op` in the current dispenser block. It returns a RequestMatcher and an error if any.

type ResponseBuffer Uses

type ResponseBuffer struct {
    Buffer *bytes.Buffer
    // contains filtered or unexported fields

ResponseBuffer is a type that conditionally buffers the response in memory. It implements http.ResponseWriter so that it can stream the response if it is not buffering. Whether it buffers is decided by a func passed into the constructor, NewResponseBuffer.

This type implements http.ResponseWriter, so you can pass this to the Next() middleware in the chain and record its response. However, since the entire response body will be buffered in memory, only use this when explicitly configured and required for some specific reason. For example, the text/template package only parses templates out of []byte and not io.Reader, so the templates directive uses this type to obtain the entire template text, but only on certain requests that match the right Content-Type, etc.

ResponseBuffer also implements io.ReaderFrom for performance reasons. The standard lib's http.response type (unexported) uses io.Copy to write the body. io.Copy makes an allocation if the destination does not have a ReadFrom method (or if the source does not have a WriteTo method, but that's irrelevant here). Our ReadFrom is smart: if buffering, it calls the buffer's ReadFrom, which makes no allocs because it is already a buffer! If we're streaming the response instead, ReadFrom uses io.CopyBuffer with a pooled buffer that is managed within this package.

func NewResponseBuffer Uses

func NewResponseBuffer(buf *bytes.Buffer, rw http.ResponseWriter,
    shouldBuffer func(status int, header http.Header) bool) *ResponseBuffer

NewResponseBuffer returns a new ResponseBuffer that will use buf to store the full body of the response if shouldBuffer returns true. If shouldBuffer returns false, then the response body will be streamed directly to rw.

shouldBuffer will be passed the status code and header fields of the response. With that information, the function should decide whether to buffer the response in memory. For example: the templates directive uses this to determine whether the response is the right Content-Type (according to user config) for a template.

For performance, the buf you pass in should probably be obtained from a sync.Pool in order to reuse allocated space.

func (*ResponseBuffer) Buffered Uses

func (rb *ResponseBuffer) Buffered() bool

Buffered returns whether rb has decided to buffer the response.

func (*ResponseBuffer) CopyHeader Uses

func (rb *ResponseBuffer) CopyHeader()

CopyHeader copies the buffered header in rb to the ResponseWriter, but it does not write the header out.

func (*ResponseBuffer) Header Uses

func (rb *ResponseBuffer) Header() http.Header

Header returns the response header map.

func (*ResponseBuffer) ReadFrom Uses

func (rb *ResponseBuffer) ReadFrom(src io.Reader) (int64, error)

ReadFrom avoids allocations when writing to the buffer (if buffering), and reduces allocations when writing to the ResponseWriter directly (if streaming).

In local testing with the templates directive, req/sec were improved from ~8,200 to ~9,600 on templated files by ensuring that this type implements io.ReaderFrom.

func (*ResponseBuffer) StatusCodeWriter Uses

func (rb *ResponseBuffer) StatusCodeWriter(w http.ResponseWriter) http.ResponseWriter

StatusCodeWriter returns an http.ResponseWriter that always writes the status code stored in rb from when a response was buffered to it.

func (*ResponseBuffer) Write Uses

func (rb *ResponseBuffer) Write(buf []byte) (int, error)

Write writes buf to rb.Buffer if buffering, otherwise to the ResponseWriter directly if streaming.

func (*ResponseBuffer) WriteHeader Uses

func (rb *ResponseBuffer) WriteHeader(status int)

WriteHeader calls shouldBuffer to decide whether the upcoming body should be buffered, and then writes the header to the response.

type ResponseRecorder Uses

type ResponseRecorder struct {
    Replacer Replacer
    // contains filtered or unexported fields

ResponseRecorder is a type of http.ResponseWriter that captures the status code written to it and also the size of the body written in the response. A status code does not have to be written, however, in which case 200 must be assumed. It is best to have the constructor initialize this type with that default status code.

Setting the Replacer field allows middlewares to type-assert the http.ResponseWriter to ResponseRecorder and set their own placeholder values for logging utilities to use.

Beware when accessing the Replacer value; it may be nil!

func NewResponseRecorder Uses

func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder

NewResponseRecorder makes and returns a new ResponseRecorder. Because a status is not set unless WriteHeader is called explicitly, this constructor initializes with a status code of 200 to cover the default case.

func (*ResponseRecorder) Size Uses

func (r *ResponseRecorder) Size() int

Size returns the size of the recorded response body.

func (*ResponseRecorder) Status Uses

func (r *ResponseRecorder) Status() int

Status returns the recorded response status code.

func (*ResponseRecorder) Write Uses

func (r *ResponseRecorder) Write(buf []byte) (int, error)

Write is a wrapper that records the size of the body that gets written.

func (*ResponseRecorder) WriteHeader Uses

func (r *ResponseRecorder) WriteHeader(status int)

WriteHeader records the status code and calls the underlying ResponseWriter's WriteHeader method.

type ResponseWriterWrapper Uses

type ResponseWriterWrapper struct {

ResponseWriterWrapper wrappers underlying ResponseWriter and inherits its Hijacker/Pusher/CloseNotifier/Flusher as well.

func (*ResponseWriterWrapper) CloseNotify Uses

func (rww *ResponseWriterWrapper) CloseNotify() <-chan bool

CloseNotify implements http.CloseNotifier. It just inherits the underlying ResponseWriter's CloseNotify method. It panics if the underlying ResponseWriter is not a CloseNotifier.

func (*ResponseWriterWrapper) Flush Uses

func (rww *ResponseWriterWrapper) Flush()

Flush implements http.Flusher. It simply wraps the underlying ResponseWriter's Flush method if there is one, or panics.

func (*ResponseWriterWrapper) Hijack Uses

func (rww *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements http.Hijacker. It simply wraps the underlying ResponseWriter's Hijack method if there is one, or returns an error.

func (*ResponseWriterWrapper) Push Uses

func (rww *ResponseWriterWrapper) Push(target string, opts *http.PushOptions) error

Push implements http.Pusher. It just inherits the underlying ResponseWriter's Push method. It panics if the underlying ResponseWriter is not a Pusher.

type Server Uses

type Server struct {
    Server *http.Server
    // contains filtered or unexported fields

Server is the HTTP server implementation.

func NewServer Uses

func NewServer(addr string, group []*SiteConfig) (*Server, error)

NewServer creates a new Server instance that will listen on addr and will serve the sites configured in group.

func (*Server) Address Uses

func (s *Server) Address() string

Address returns the address s was assigned to listen on.

func (*Server) Listen Uses

func (s *Server) Listen() (net.Listener, error)

Listen creates an active listener for s that can be used to serve requests.

func (*Server) ListenPacket Uses

func (s *Server) ListenPacket() (net.PacketConn, error)

ListenPacket creates udp connection for QUIC if it is enabled,

func (*Server) OnStartupComplete Uses

func (s *Server) OnStartupComplete()

OnStartupComplete lists the sites served by this server and any relevant information, assuming caddy.Quiet == false.

func (*Server) Serve Uses

func (s *Server) Serve(ln net.Listener) error

Serve serves requests on ln. It blocks until ln is closed.

func (*Server) ServeHTTP Uses

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the entry point of all HTTP requests.

func (*Server) ServePacket Uses

func (s *Server) ServePacket(pc net.PacketConn) error

ServePacket serves QUIC requests on pc until it is closed.

func (*Server) Stop Uses

func (s *Server) Stop() error

Stop stops s gracefully (or forcefully after timeout) and closes its listener.

func (*Server) WrapListener Uses

func (s *Server) WrapListener(ln net.Listener) net.Listener

WrapListener wraps ln in the listener middlewares configured for this server.

type SiteConfig Uses

type SiteConfig struct {
    // The address of the site
    Addr Address

    // The list of viable index page names of the site
    IndexPages []string

    // The hostname to bind listener to;
    // defaults to Addr.Host
    ListenHost string

    // TLS configuration
    TLS *caddytls.Config

    // If true, the Host header in the HTTP request must
    // match the SNI value in the TLS handshake (if any).
    // This should be enabled whenever a site relies on
    // TLS client authentication, for example; or any time
    // you want to enforce that THIS site's TLS config
    // is used and not the TLS config of any other site
    // on the same listener. TODO: Check how relevant this
    // is with TLS 1.3.
    StrictHostMatching bool

    // Directory from which to serve files
    Root string

    // A list of files to hide (for example, the
    // source Caddyfile). TODO: Enforcing this
    // should be centralized, for example, a
    // standardized way of loading files from disk
    // for a request.
    HiddenFiles []string

    // Max request's header/body size
    Limits Limits

    // These timeout values are used, in conjunction with other
    // site configs on the same server instance, to set the
    // respective timeout values on the http.Server that
    // is created. Sensible values will mitigate slowloris
    // attacks and overcome faulty networks, while still
    // preserving functionality needed for proxying,
    // websockets, etc.
    Timeouts Timeouts

    // If true, any requests not matching other site definitions
    // may be served by this site.
    FallbackSite bool
    // contains filtered or unexported fields

SiteConfig contains information about a site (also known as a virtual host).

func GetConfig Uses

func GetConfig(c *caddy.Controller) *SiteConfig

GetConfig gets the SiteConfig that corresponds to c. If none exist (should only happen in tests), then a new, empty one will be created.

func (*SiteConfig) AddListenerMiddleware Uses

func (s *SiteConfig) AddListenerMiddleware(l ListenerMiddleware)

AddListenerMiddleware adds a listener middleware to a site's listenerMiddleware stack.

func (*SiteConfig) AddMiddleware Uses

func (s *SiteConfig) AddMiddleware(m Middleware)

AddMiddleware adds a middleware to a site's middleware stack.

func (SiteConfig) Host Uses

func (s SiteConfig) Host() string

Host returns s.Addr.Host.

func (SiteConfig) ListenerMiddleware Uses

func (s SiteConfig) ListenerMiddleware() []ListenerMiddleware

ListenerMiddleware returns s.listenerMiddleware

func (SiteConfig) Middleware Uses

func (s SiteConfig) Middleware() []Middleware

Middleware returns s.middleware (useful for tests).

func (SiteConfig) Port Uses

func (s SiteConfig) Port() string

Port returns s.Addr.Port.

func (SiteConfig) TLSConfig Uses

func (s SiteConfig) TLSConfig() *caddytls.Config

TLSConfig returns s.TLS.

type Timeouts Uses

type Timeouts struct {
    ReadTimeout          time.Duration
    ReadTimeoutSet       bool
    ReadHeaderTimeout    time.Duration
    ReadHeaderTimeoutSet bool
    WriteTimeout         time.Duration
    WriteTimeoutSet      bool
    IdleTimeout          time.Duration
    IdleTimeoutSet       bool

Timeouts specify various timeouts for a server to use. If the associated bool field is true, then the duration value should be treated literally (i.e. a zero-value duration would mean "no timeout"). If false, the duration was left unset, so a zero-value duration would mean to use a default value (even if default is non-zero).

Package httpserver imports 39 packages (graph) and is imported by 2817 packages. Updated 2020-01-18. Refresh now. Tools for package owners.