{"modulePath":"github.com/caddyserver/caddy","version":"v1.0.5","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package httpserver\n\nPackage httpserver implements an HTTP server on top of Caddy.\n\n## Constants\n\n```go\nconst (\n\t// ReplacerCtxKey is the context key for a per-request replacer.\n\tReplacerCtxKey caddy.CtxKey = \"replacer\"\n\n\t// RemoteUserCtxKey is the key for the remote user of the request, if any (basicauth).\n\tRemoteUserCtxKey caddy.CtxKey = \"remote_user\"\n\n\t// MitmCtxKey is the key for the result of MITM detection\n\tMitmCtxKey caddy.CtxKey = \"mitm\"\n\n\t// RequestIDCtxKey is the key for the U4 UUID value\n\tRequestIDCtxKey caddy.CtxKey = \"request_id\"\n)\n```\nContext key constants.\n\n```go\nconst (\n\n\t// cipher suites missing from the crypto/tls package,\n\t// in no particular order here\n\tTLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xc024\n\tTLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   = 0xc028\n\tTLS_RSA_WITH_AES_256_CBC_SHA256         = 0x3d\n\tTLS_DHE_RSA_WITH_AES_128_CBC_SHA        = 0x33\n\tTLS_DHE_RSA_WITH_AES_256_CBC_SHA        = 0x39\n\tTLS_RSA_WITH_RC4_128_MD5                = 0x4\n\n\t// new PSK ciphers introduced by TLS 1.3, not (yet) in crypto/tls\n\t// https://tlswg.github.io/tls13-spec/#rfc.appendix.A.4)\n\tTLS_AES_128_GCM_SHA256       = 0x1301\n\tTLS_AES_256_GCM_SHA384       = 0x1302\n\tTLS_CHACHA20_POLY1305_SHA256 = 0x1303\n\tTLS_AES_128_CCM_SHA256       = 0x1304\n\tTLS_AES_128_CCM_8_SHA256     = 0x1305\n)\n```\nDefine variables used for TLS communication\n\n```go\nconst (\n\t// DefaultHost is the default host.\n\tDefaultHost = \"\"\n\t// DefaultPort is the default port.\n\tDefaultPort = \"2015\"\n\t// DefaultRoot is the default root folder.\n\tDefaultRoot = \".\"\n\t// DefaultHTTPPort is the default port for HTTP.\n\tDefaultHTTPPort = \"80\"\n\t// DefaultHTTPSPort is the default port for HTTPS.\n\tDefaultHTTPSPort = \"443\"\n)\n```\n\n```go\nconst (\n\n\t// MaxLogBodySize limits the size of logged request's body\n\tMaxLogBodySize = 100 * 1024\n)\n```\n\n```go\nconst OriginalURLCtxKey = caddy.CtxKey(\"original_url\")\n```\nOriginalURLCtxKey is the key for accessing the original, incoming URL on an HTTP request.\n\n## Variables\n\n```go\nvar (\n\t// Root is the site root\n\tRoot = DefaultRoot\n\n\t// Host is the site host\n\tHost = DefaultHost\n\n\t// Port is the site port\n\tPort = DefaultPort\n\n\t// GracefulTimeout is the maximum duration of a graceful shutdown.\n\tGracefulTimeout time.Duration\n\n\t// HTTP2 indicates whether HTTP2 is enabled or not.\n\tHTTP2 bool\n\n\t// QUIC indicates whether QUIC is enabled or not.\n\tQUIC bool\n)\n```\nThese \"soft defaults\" are configurable by command line flags, etc.\n\n```go\nvar CaseSensitivePath = false\n```\nCaseSensitivePath determines if paths should be case sensitive. This is configurable via CASE\\_SENSITIVE\\_PATH environment variable.\n\n```go\nvar EmptyNext = HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) { return 0, nil })\n```\nEmptyNext 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.\n\nUsed primarily for testing but needs to be exported so plugins can use this as a convenience.\n\n```go\nvar ErrMaxBytesExceeded = errors.New(\"http: request body too large\")\n```\nErrMaxBytesExceeded is the error returned by MaxBytesReader when the request body exceeds the limit imposed\n\n```go\nvar TemplateFuncs = template.FuncMap{}\n```\nTemplateFuncs contains user-defined functions for execution in templates.\n\n## Functions\n\n```go\nfunc ContextInclude(filename string, ctx interface{}, fs http.FileSystem) (string, error)\n```\nContextInclude 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.\n\n```go\nfunc DefaultErrorFunc(w http.ResponseWriter, r *http.Request, status int)\n```\nDefaultErrorFunc responds to an HTTP request with a simple description of the specified HTTP status code.\n\n```go\nfunc IfMatcherKeyword(c *caddy.Controller) bool\n```\nIfMatcherKeyword 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.\n\n```go\nfunc IndexFile(root http.FileSystem, fpath string, indexFiles []string) (string, bool)\n```\nIndexFile 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).\n\nAll 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.\n\n```go\nfunc IsLogRollerSubdirective(subdir string) bool\n```\nIsLogRollerSubdirective is true if the subdirective is for the log roller.\n\n```go\nfunc ParseRoller(l *LogRoller, what string, where ...string) error\n```\nParseRoller parses roller contents out of c.\n\n```go\nfunc RegisterDevDirective(name, before string)\n```\nRegisterDevDirective 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.\n\nIt 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.\n\nDirective 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.\n\n```go\nfunc SafePath(siteRoot, reqPath string) string\n```\nSafePath 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.\n\nIf opening a file, use http.Dir instead.\n\n```go\nfunc SameNext(next1, next2 Handler) bool\n```\nSameNext does a pointer comparison between next1 and next2.\n\nUsed primarily for testing but needs to be exported so plugins can use this as a convenience.\n\n```go\nfunc SetLastModifiedHeader(w http.ResponseWriter, modTime time.Time)\n```\nSetLastModifiedHeader 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.\n\n```go\nfunc WriteSiteNotFound(w http.ResponseWriter, r *http.Request)\n```\nWriteSiteNotFound writes appropriate error code to w, signaling that requested host is not served by Caddy on a given port.\n\n```go\nfunc WriteTextResponse(w http.ResponseWriter, status int, body string)\n```\nWriteTextResponse writes body with code status to w. The body will be interpreted as plain text.\n\n## Types\n\n```go\ntype Address struct {\n\tOriginal, Scheme, Host, Port, Path string\n}\n```\nAddress 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.\n\nThe Host field must be in a normalized form.\n\n```go\nfunc (a Address) Key() string\n```\nKey is similar to String, just replaces scheme and host values with modified values. Unlike String it doesn't add anything default (scheme, port, etc)\n\n```go\nfunc (a Address) Normalize() Address\n```\nNormalize normalizes URL: turn scheme and host names into lower case\n\n```go\nfunc (a Address) String() string\n```\nString returns a human-friendly print of the address.\n\n```go\nfunc (a Address) VHost() string\n```\nVHost returns a sensible concatenation of Host:Port/Path from a. It's basically the a.Original but without the scheme.\n\n```go\ntype ConfigSelector []HandlerConfig\n```\nConfigSelector selects a configuration.\n\n```go\nfunc (c ConfigSelector) Select(r *http.Request) (config HandlerConfig)\n```\nSelect selects a Config. This chooses the config with the longest length.\n\n```go\ntype Context struct {\n\tRoot http.FileSystem\n\tReq  *http.Request\n\tURL  *url.URL\n\tArgs []interface{} // defined by arguments to .Include\n\t// contains filtered or unexported fields\n}\n```\nContext is the context with which Caddy templates are executed.\n\n```go\nfunc NewContextWithHeader(rh http.Header) Context\n```\nNewContextWithHeader creates a context with given response header.\n\nTo plugin developer: The returned context's exported fileds remain empty, you should then initialize them if you want.\n\n```go\nfunc (c Context) AddLink(link string) string\n```\nAddLink adds a link header in response see [https://www.w3.org/wiki/LinkHeader](https://www.w3.org/wiki/LinkHeader)\n\n```go\nfunc (c Context) Cookie(name string) string\n```\nCookie gets the value of a cookie with name name.\n\n```go\nfunc (c Context) Env() map[string]string\n```\nEnv gets a map of the environment variables.\n\n```go\nfunc (c Context) Ext(pathStr string) string\n```\nExt returns the suffix beginning at the final dot in the final slash-separated element of the pathStr (or in other words, the file extension).\n\n```go\nfunc (c Context) Files(name string) ([]string, error)\n```\nFiles reads and returns a slice of names from the given directory relative to the root of Context c.\n\n```go\nfunc (c Context) Header(name string) string\n```\nHeader gets the value of a request header with field name.\n\n```go\nfunc (c Context) Host() (string, error)\n```\nHost returns the hostname portion of the Host header from the HTTP request.\n\n```go\nfunc (c Context) Hostname() string\n```\nHostname gets the (remote) hostname of the client making the request.\n\n```go\nfunc (c Context) IP() string\n```\nIP gets the (remote) IP address of the client making the request.\n\n```go\nfunc (c Context) Include(filename string, args ...interface{}) (string, error)\n```\nInclude returns the contents of filename relative to the site root.\n\n```go\nfunc (c Context) IsMITM() bool\n```\nIsMITM returns true if it seems likely that the TLS connection is being intercepted.\n\n```go\nfunc (c Context) Join(a []string, sep string) string\n```\nJoin 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.\n\n```go\nfunc (c Context) Map(values ...interface{}) (map[string]interface{}, error)\n```\nMap 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.\n\n```go\nfunc (c Context) Markdown(filename string) (string, error)\n```\nMarkdown returns the HTML contents of the markdown contained in filename (relative to the site root).\n\n```go\nfunc (c Context) Method() string\n```\nMethod returns the method (GET, POST, etc.) of the request.\n\n```go\nfunc (c Context) Now(format string) string\n```\nNow returns the current timestamp in the specified format.\n\n```go\nfunc (c Context) NowDate() time.Time\n```\nNowDate returns the current date/time that can be used in other time functions.\n\n```go\nfunc (c Context) PathMatches(pattern string) bool\n```\nPathMatches returns true if the path portion of the request URL matches pattern.\n\n```go\nfunc (c Context) Port() (string, error)\n```\nPort returns the port portion of the Host header if specified.\n\n```go\nfunc (c Context) RandomString(minLen, maxLen int) string\n```\nRandomString generates a random string of random length given length bounds. Thanks to [http://stackoverflow.com/a/35615565/1048862](http://stackoverflow.com/a/35615565/1048862) for the clever technique that is fairly fast, secure, and maintains proper distributions over the dictionary.\n\n```go\nfunc (c Context) Replace(input, find, replacement string) string\n```\nReplace replaces instances of find in input with replacement.\n\n```go\nfunc (c Context) ServerIP() string\n```\nServerIP gets the (local) IP address of the server. TODO: The bind directive should be honored in this method (see PR #1474).\n\n```go\nfunc (c Context) Slice(elems ...interface{}) []interface{}\n```\nSlice will convert the given arguments into a slice.\n\n```go\nfunc (c Context) Split(s string, sep string) []string\n```\nSplit 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.\n\n```go\nfunc (c Context) StripExt(path string) string\n```\nStripExt 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.\n\n```go\nfunc (c Context) StripHTML(s string) string\n```\nStripHTML returns s without HTML tags. It is fairly naive but works with most valid HTML inputs.\n\n```go\nfunc (c Context) TLSVersion() (ret string)\n```\nReturns either TLS protocol version if TLS used or empty string otherwise\n\n```go\nfunc (c Context) ToLower(s string) string\n```\nToLower will convert the given string to lower case.\n\n```go\nfunc (c Context) ToUpper(s string) string\n```\nToUpper will convert the given string to upper case.\n\n```go\nfunc (c Context) Truncate(input string, length int) string\n```\nTruncate 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.\n\n```go\nfunc (c Context) URI() string\n```\nURI returns the raw, unprocessed request URI (including query string and hash) obtained directly from the Request-Line of the HTTP request.\n\n```go\ntype HTTPInterfaces interface {\n\thttp.ResponseWriter\n\thttp.Pusher\n\thttp.Flusher\n\thttp.CloseNotifier\n\thttp.Hijacker\n}\n```\nHTTPInterfaces mix all the interfaces that middleware ResponseWriters need to support.\n\n```go\ntype Handler interface {\n\tServeHTTP(http.ResponseWriter, *http.Request) (int, error)\n}\n```\nHandler is like http.Handler except ServeHTTP may return a status code and/or error.\n\nIf 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.\n\nIf ServeHTTP encounters an error, it should return the error value so it can be logged by designated error-handling middleware.\n\nIf writing a response after calling the next ServeHTTP method, the returned status code SHOULD be used when writing the response.\n\nIf handling errors after calling the next ServeHTTP method, the returned error value SHOULD be logged or handled accordingly.\n\nOtherwise, return values should be propagated down the middleware chain by returning them unchanged.\n\n```go\ntype HandlerConfig interface {\n\tRequestMatcher\n\tBasePath() string\n}\n```\nHandlerConfig is a middleware configuration. This makes it possible for middlewares to have a common configuration interface.\n\nTODO The long term plan is to get all middleware implement this interface for configurations.\n\n```go\ntype HandlerFunc func(http.ResponseWriter, *http.Request) (int, error)\n```\nHandlerFunc is a convenience type like http.HandlerFunc, except ServeHTTP returns a status code and an error. See Handler documentation for more information.\n\n```go\nfunc (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)\n```\nServeHTTP implements the Handler interface.\n\n```go\ntype IfMatcher struct {\n\tEnabled bool // if true, matcher has been configured; otherwise it's no-op\n\t// contains filtered or unexported fields\n}\n```\nIfMatcher is a RequestMatcher for 'if' conditions.\n\n```go\nfunc (m IfMatcher) And(r *http.Request) bool\n```\nAnd returns true if all conditions in m are true.\n\n```go\nfunc (m IfMatcher) Match(r *http.Request) bool\n```\nMatch satisfies RequestMatcher interface. It returns true if the conditions in m are true.\n\n```go\nfunc (m IfMatcher) Or(r *http.Request) bool\n```\nOr returns true if any of the conditions in m is true.\n\n```go\ntype Limits struct {\n\tMaxRequestHeaderSize int64\n\tMaxRequestBodySizes  []PathLimit\n}\n```\nLimits specify size limit of request's header and body.\n\n```go\ntype ListenerMiddleware func(caddy.Listener) caddy.Listener\n```\nListenerMiddleware is similar to the Middleware type, except it chains one net.Listener to the next.\n\n```go\ntype LogRoller struct {\n\tDisabled   bool\n\tFilename   string\n\tMaxSize    int\n\tMaxAge     int\n\tMaxBackups int\n\tCompress   bool\n\tLocalTime  bool\n}\n```\nLogRoller implements a type that provides a rolling logger.\n\n```go\nfunc DefaultLogRoller() *LogRoller\n```\nDefaultLogRoller will roll logs by default.\n\n```go\nfunc (l LogRoller) GetLogWriter() io.Writer\n```\nGetLogWriter 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.\n\n```go\ntype Logger struct {\n\tOutput string\n\t*log.Logger\n\tRoller *LogRoller\n\n\tV4ipMask     net.IPMask\n\tV6ipMask     net.IPMask\n\tIPMaskExists bool\n\tExceptions   []string\n\t// contains filtered or unexported fields\n}\n```\nLogger is shared between errors and log plugins and supports both logging to a file (with an optional file roller), local and remote syslog servers.\n\n```go\nfunc NewTestLogger(buffer *bytes.Buffer) *Logger\n```\nNewTestLogger creates logger suitable for testing purposes\n\n```go\nfunc (l *Logger) Attach(controller *caddy.Controller)\n```\nAttach binds logger Start and Close functions to controller's OnStartup and OnShutdown hooks.\n\n```go\nfunc (l *Logger) Close() error\n```\nClose closes open log files or connections to syslog.\n\n```go\nfunc (l Logger) MaskIP(ip string) string\n```\n\n```go\nfunc (l Logger) Printf(format string, args ...interface{})\n```\nPrintf wraps underlying logger with mutex\n\n```go\nfunc (l Logger) Println(args ...interface{})\n```\nPrintln wraps underlying logger with mutex\n\n```go\nfunc (l Logger) ShouldLog(path string) bool\n```\nShouldLog returns true if the path is not exempted from being logged (i.e. it is not found in l.Exceptions).\n\n```go\nfunc (l *Logger) Start() error\n```\nStart initializes logger opening files or local/remote syslog connections\n\n```go\ntype Middleware func(Handler) Handler\n```\nMiddleware 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.\n\n```go\ntype NonCloseNotifierError struct {\n\t// underlying type which doesn't implement CloseNotify\n\tUnderlying interface{}\n}\n```\nNonCloseNotifierError is more descriptive error caused by a non closeNotifier\n\n```go\nfunc (c NonCloseNotifierError) Error() string\n```\nImplement Error\n\n```go\ntype NonFlusherError struct {\n\t// underlying type which doesn't implement Flush\n\tUnderlying interface{}\n}\n```\nNonFlusherError is more descriptive error caused by a non flusher\n\n```go\nfunc (f NonFlusherError) Error() string\n```\nImplement Error\n\n```go\ntype NonHijackerError struct {\n\t// underlying type which doesn't implement Hijack\n\tUnderlying interface{}\n}\n```\nNonHijackerError is more descriptive error caused by a non hijacker\n\n```go\nfunc (h NonHijackerError) Error() string\n```\nImplement Error\n\n```go\ntype NonPusherError struct {\n\t// underlying type which doesn't implement pusher\n\tUnderlying interface{}\n}\n```\nNonPusherError is more descriptive error caused by a non pusher\n\n```go\nfunc (c NonPusherError) Error() string\n```\nImplement Error\n\n```go\ntype Path string\n```\nPath represents a URI path. It should usually be set to the value of a request path.\n\n```go\nfunc (p Path) Matches(base string) bool\n```\nMatches 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.\n\nPath matching will probably not always be a direct comparison; this method assures that paths can be easily and consistently matched.\n\nMultiple slashes are collapsed/merged. See issue #1859.\n\n```go\ntype PathLimit struct {\n\tPath  string\n\tLimit int64\n}\n```\nPathLimit is a mapping from a site's path to its corresponding maximum request body size (in bytes)\n\n```go\ntype PathMatcher string\n```\nPathMatcher is a Path RequestMatcher.\n\n```go\nfunc (p PathMatcher) Match(r *http.Request) bool\n```\nMatch satisfies RequestMatcher.\n\n```go\ntype Replacer interface {\n\tReplace(string) string\n\tSet(key, value string)\n}\n```\nReplacer 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.\n\n```go\nfunc NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Replacer\n```\nNewReplacer 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).\n\n```go\ntype RequestMatcher interface {\n\tMatch(r *http.Request) bool\n}\n```\nRequestMatcher checks to see if current request should be handled by underlying handler.\n\n```go\nfunc MergeRequestMatchers(matchers ...RequestMatcher) RequestMatcher\n```\nMergeRequestMatchers merges multiple RequestMatchers into one. This allows a middleware to use multiple RequestMatchers.\n\n```go\nfunc SetupIfMatcher(controller *caddy.Controller) (RequestMatcher, error)\n```\nSetupIfMatcher parses \\`if\\` or \\`if\\_op\\` in the current dispenser block. It returns a RequestMatcher and an error if any.\n\n```go\ntype ResponseBuffer struct {\n\t*ResponseWriterWrapper\n\tBuffer *bytes.Buffer\n\t// contains filtered or unexported fields\n}\n```\nResponseBuffer 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.\n\nThis 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.\n\nResponseBuffer 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.\n\n```go\nfunc NewResponseBuffer(buf *bytes.Buffer, rw http.ResponseWriter,\n\tshouldBuffer func(status int, header http.Header) bool) *ResponseBuffer\n```\nNewResponseBuffer 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.\n\nshouldBuffer 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.\n\nFor performance, the buf you pass in should probably be obtained from a sync.Pool in order to reuse allocated space.\n\n```go\nfunc (rb *ResponseBuffer) Buffered() bool\n```\nBuffered returns whether rb has decided to buffer the response.\n\n```go\nfunc (rb *ResponseBuffer) CopyHeader()\n```\nCopyHeader copies the buffered header in rb to the ResponseWriter, but it does not write the header out.\n\n```go\nfunc (rb *ResponseBuffer) Header() http.Header\n```\nHeader returns the response header map.\n\n```go\nfunc (rb *ResponseBuffer) ReadFrom(src io.Reader) (int64, error)\n```\nReadFrom avoids allocations when writing to the buffer (if buffering), and reduces allocations when writing to the ResponseWriter directly (if streaming).\n\nIn 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.\n\n```go\nfunc (rb *ResponseBuffer) StatusCodeWriter(w http.ResponseWriter) http.ResponseWriter\n```\nStatusCodeWriter returns an http.ResponseWriter that always writes the status code stored in rb from when a response was buffered to it.\n\n```go\nfunc (rb *ResponseBuffer) Write(buf []byte) (int, error)\n```\nWrite writes buf to rb.Buffer if buffering, otherwise to the ResponseWriter directly if streaming.\n\n```go\nfunc (rb *ResponseBuffer) WriteHeader(status int)\n```\nWriteHeader calls shouldBuffer to decide whether the upcoming body should be buffered, and then writes the header to the response.\n\n```go\ntype ResponseRecorder struct {\n\t*ResponseWriterWrapper\n\tReplacer Replacer\n\t// contains filtered or unexported fields\n}\n```\nResponseRecorder 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.\n\nSetting the Replacer field allows middlewares to type-assert the http.ResponseWriter to ResponseRecorder and set their own placeholder values for logging utilities to use.\n\nBeware when accessing the Replacer value; it may be nil!\n\n```go\nfunc NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder\n```\nNewResponseRecorder 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.\n\n```go\nfunc (r *ResponseRecorder) Size() int\n```\nSize returns the size of the recorded response body.\n\n```go\nfunc (r *ResponseRecorder) Status() int\n```\nStatus returns the recorded response status code.\n\n```go\nfunc (r *ResponseRecorder) Write(buf []byte) (int, error)\n```\nWrite is a wrapper that records the size of the body that gets written.\n\n```go\nfunc (r *ResponseRecorder) WriteHeader(status int)\n```\nWriteHeader records the status code and calls the underlying ResponseWriter's WriteHeader method.\n\n```go\ntype ResponseWriterWrapper struct {\n\thttp.ResponseWriter\n}\n```\nResponseWriterWrapper wrappers underlying ResponseWriter and inherits its Hijacker/Pusher/CloseNotifier/Flusher as well.\n\n```go\nfunc (rww *ResponseWriterWrapper) CloseNotify() \u003c-chan bool\n```\nCloseNotify implements http.CloseNotifier. It just inherits the underlying ResponseWriter's CloseNotify method. It panics if the underlying ResponseWriter is not a CloseNotifier.\n\n```go\nfunc (rww *ResponseWriterWrapper) Flush()\n```\nFlush implements http.Flusher. It simply wraps the underlying ResponseWriter's Flush method if there is one, or panics.\n\n```go\nfunc (rww *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error)\n```\nHijack implements http.Hijacker. It simply wraps the underlying ResponseWriter's Hijack method if there is one, or returns an error.\n\n```go\nfunc (rww *ResponseWriterWrapper) Push(target string, opts *http.PushOptions) error\n```\nPush implements http.Pusher. It just inherits the underlying ResponseWriter's Push method. It panics if the underlying ResponseWriter is not a Pusher.\n\n```go\ntype Server struct {\n\tServer *http.Server\n\t// contains filtered or unexported fields\n}\n```\nServer is the HTTP server implementation.\n\n```go\nfunc NewServer(addr string, group []*SiteConfig) (*Server, error)\n```\nNewServer creates a new Server instance that will listen on addr and will serve the sites configured in group.\n\n```go\nfunc (s *Server) Address() string\n```\nAddress returns the address s was assigned to listen on.\n\n```go\nfunc (s *Server) Listen() (net.Listener, error)\n```\nListen creates an active listener for s that can be used to serve requests.\n\n```go\nfunc (s *Server) ListenPacket() (net.PacketConn, error)\n```\nListenPacket creates udp connection for QUIC if it is enabled,\n\n```go\nfunc (s *Server) OnStartupComplete()\n```\nOnStartupComplete lists the sites served by this server and any relevant information, assuming caddy.Quiet == false.\n\n```go\nfunc (s *Server) Serve(ln net.Listener) error\n```\nServe serves requests on ln. It blocks until ln is closed.\n\n```go\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\nServeHTTP is the entry point of all HTTP requests.\n\n```go\nfunc (s *Server) ServePacket(pc net.PacketConn) error\n```\nServePacket serves QUIC requests on pc until it is closed.\n\n```go\nfunc (s *Server) Stop() error\n```\nStop stops s gracefully (or forcefully after timeout) and closes its listener.\n\n```go\nfunc (s *Server) WrapListener(ln net.Listener) net.Listener\n```\nWrapListener wraps ln in the listener middlewares configured for this server.\n\n```go\ntype SiteConfig struct {\n\t// The address of the site\n\tAddr Address\n\n\t// The list of viable index page names of the site\n\tIndexPages []string\n\n\t// The hostname to bind listener to;\n\t// defaults to Addr.Host\n\tListenHost string\n\n\t// TLS configuration\n\tTLS *caddytls.Config\n\n\t// If true, the Host header in the HTTP request must\n\t// match the SNI value in the TLS handshake (if any).\n\t// This should be enabled whenever a site relies on\n\t// TLS client authentication, for example; or any time\n\t// you want to enforce that THIS site's TLS config\n\t// is used and not the TLS config of any other site\n\t// on the same listener. TODO: Check how relevant this\n\t// is with TLS 1.3.\n\tStrictHostMatching bool\n\n\t// Directory from which to serve files\n\tRoot string\n\n\t// A list of files to hide (for example, the\n\t// source Caddyfile). TODO: Enforcing this\n\t// should be centralized, for example, a\n\t// standardized way of loading files from disk\n\t// for a request.\n\tHiddenFiles []string\n\n\t// Max request's header/body size\n\tLimits Limits\n\n\t// These timeout values are used, in conjunction with other\n\t// site configs on the same server instance, to set the\n\t// respective timeout values on the http.Server that\n\t// is created. Sensible values will mitigate slowloris\n\t// attacks and overcome faulty networks, while still\n\t// preserving functionality needed for proxying,\n\t// websockets, etc.\n\tTimeouts Timeouts\n\n\t// If true, any requests not matching other site definitions\n\t// may be served by this site.\n\tFallbackSite bool\n\t// contains filtered or unexported fields\n}\n```\nSiteConfig contains information about a site (also known as a virtual host).\n\n```go\nfunc GetConfig(c *caddy.Controller) *SiteConfig\n```\nGetConfig gets the SiteConfig that corresponds to c. If none exist (should only happen in tests), then a new, empty one will be created.\n\n```go\nfunc (s *SiteConfig) AddListenerMiddleware(l ListenerMiddleware)\n```\nAddListenerMiddleware adds a listener middleware to a site's listenerMiddleware stack.\n\n```go\nfunc (s *SiteConfig) AddMiddleware(m Middleware)\n```\nAddMiddleware adds a middleware to a site's middleware stack.\n\n```go\nfunc (s SiteConfig) Host() string\n```\nHost returns s.Addr.Host.\n\n```go\nfunc (s SiteConfig) ListenerMiddleware() []ListenerMiddleware\n```\nListenerMiddleware returns s.listenerMiddleware\n\n```go\nfunc (s SiteConfig) Middleware() []Middleware\n```\nMiddleware returns s.middleware (useful for tests).\n\n```go\nfunc (s SiteConfig) Port() string\n```\nPort returns s.Addr.Port.\n\n```go\nfunc (s SiteConfig) TLSConfig() *caddytls.Config\n```\nTLSConfig returns s.TLS.\n\n```go\ntype Timeouts struct {\n\tReadTimeout          time.Duration\n\tReadTimeoutSet       bool\n\tReadHeaderTimeout    time.Duration\n\tReadHeaderTimeoutSet bool\n\tWriteTimeout         time.Duration\n\tWriteTimeoutSet      bool\n\tIdleTimeout          time.Duration\n\tIdleTimeoutSet       bool\n}\n```\nTimeouts 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).\n\n","path":"github.com/caddyserver/caddy/caddyhttp/httpserver","name":"httpserver","synopsis":"Package httpserver implements an HTTP server on top of Caddy.","isRedistributable":true}
