{"modulePath":"github.com/morephp/caddy","version":"v0.9.5","isLatest":false,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package httpserver\n\nPackage httpserver implements an HTTP server on top of Caddy.\n\n## Constants\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)\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## 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 = true\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## Functions\n\n```go\nfunc CleanMaskedPath(reqPath string, masks ...string) string\n```\nCleanMaskedPath prevents one or more of the path cleanup operations:\n\n  - collapse multiple slashes into one\n  - eliminate \"/.\" (current directory)\n  - eliminate \"\\\u003cparent\\_directory\u003e/..\"\n\nby masking certain patterns in the path with a temporary random string. This could be helpful when certain patterns in the path are desired to be preserved that would otherwise be changed by path.Clean(). One such use case is the presence of the double slashes as protocol separator (e.g., /api/endpoint/[http://example.com](http://example.com)). This is a common pattern in many applications to allow passing URIs as path argument.\n\n```go\nfunc CleanPath(reqPath string) string\n```\nCleanPath calls CleanMaskedPath() with the default mask of \"://\" to preserve double slashes of protocols such as \"http://\", \"https://\", and \"ftp://\" etc.\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 dispinser are cleard 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 MaxBytesReader(w http.ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser\n```\nMaxBytesReader and its associated methods are borrowed from the Go Standard library (comments intact). The only difference is that it returns a MaxBytesExceeded error instead of a generic error message when the request body has exceeded the requested limit\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 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 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\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}\n```\nContext is the context with which Caddy templates are executed.\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) 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) 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) Replace(input, find, replacement string) string\n```\nReplace replaces instances of find in input with replacement.\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) 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 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\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 LogRoller struct {\n\tFilename   string\n\tMaxSize    int\n\tMaxAge     int\n\tMaxBackups int\n\tLocalTime  bool\n}\n```\nLogRoller implements a type that provides a rolling logger.\n\n```go\nfunc ParseRoller(c *caddy.Controller) (*LogRoller, error)\n```\nParseRoller parses roller contents out of c.\n\n```go\nfunc (l LogRoller) GetLogWriter() io.Writer\n```\nGetLogWriter returns an io.Writer that writes to a rolling logger.\n\n```go\ntype MaxBytesExceeded struct{}\n```\nMaxBytesExceeded is the error type returned by MaxBytesReader when the request body exceeds the limit imposed\n\n```go\nfunc (err MaxBytesExceeded) Error() string\n```\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 Path string\n```\nPath represents a URI path.\n\n```go\nfunc (p Path) Matches(other string) bool\n```\nMatches checks to see if other matches p.\n\nPath matching will probably not always be a direct comparison; this method assures that paths can be easily and consistently matched.\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 ResponseRecorder struct {\n\thttp.ResponseWriter\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, which captures the HTTP Status code from the ResponseWriter and also the length of the response body written through it. 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) CloseNotify() \u003c-chan bool\n```\nCloseNotify implements http.CloseNotifier. It just inherits the underlying ResponseWriter's CloseNotify method.\n\n```go\nfunc (r *ResponseRecorder) Flush()\n```\nFlush implements http.Flusher. It simply wraps the underlying ResponseWriter's Flush method if there is one, or does nothing.\n\n```go\nfunc (r *ResponseRecorder) 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 (r *ResponseRecorder) Size() int\n```\nSize is a Getter to size property\n\n```go\nfunc (r *ResponseRecorder) Status() int\n```\nStatus is a Getter to status property\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 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 is a noop to implement the Server interface.\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 is a noop to implement the Server interface.\n\n```go\nfunc (s *Server) Stop() (err error)\n```\nStop stops s gracefully (or forcefully after timeout) and closes its listener.\n\n```go\ntype SiteConfig struct {\n\t// The address of the site\n\tAddr Address\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// 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 amount of bytes a request can send on a given path\n\tMaxRequestBodySizes []PathLimit\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\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) 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) 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 assocated 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/morephp/caddy/caddyhttp/httpserver","name":"httpserver","synopsis":"Package httpserver implements an HTTP server on top of Caddy.","isRedistributable":true}
