httpserver

package
Version: v0.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2016 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package httpserver implements an HTTP server on top of Caddy.

Index

Constants

View Source
const (
	// DefaultHost is the default host.
	DefaultHost = ""
	// DefaultPort is the default port.
	DefaultPort = "2015"
	// DefaultRoot is the default root folder.
	DefaultRoot = "."
)

Variables

View Source
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.

View Source
var CaseSensitivePath = true

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

View Source
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.

Functions

func ContextInclude

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

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

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 dispinser are cleard to keep the dispenser valid for use.

func IndexFile

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 SameNext

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

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 WriteTextResponse

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.

Types

type Address

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.

func (Address) String

func (a Address) String() string

String returns a human-friendly print of the address.

func (Address) VHost

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

type ConfigSelector []HandlerConfig

ConfigSelector selects a configuration.

func (ConfigSelector) Select

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

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

type Context

type Context struct {
	Root http.FileSystem
	Req  *http.Request
	URL  *url.URL
}

Context is the context with which Caddy templates are executed.

func (Context) Cookie

func (c Context) Cookie(name string) string

Cookie gets the value of a cookie with name name.

func (Context) Env added in v0.9.1

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

Env gets a map of the environment variables.

func (Context) Ext

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) Header

func (c Context) Header(name string) string

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

func (Context) Host

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

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

func (Context) IP

func (c Context) IP() string

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

func (Context) Include

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

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

func (Context) Join added in v0.9.1

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

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

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

func (c Context) Method() string

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

func (Context) Now

func (c Context) Now(format string) string

Now returns the current timestamp in the specified format.

func (Context) NowDate

func (c Context) NowDate() time.Time

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

func (Context) PathMatches

func (c Context) PathMatches(pattern string) bool

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

func (Context) Port

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

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

func (Context) Replace

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

Replace replaces instances of find in input with replacement.

func (Context) Slice

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

Slice will convert the given arguments into a slice.

func (Context) Split

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

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

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) ToLower

func (c Context) ToLower(s string) string

ToLower will convert the given string to lower case.

func (Context) ToUpper

func (c Context) ToUpper(s string) string

ToUpper will convert the given string to upper case.

func (Context) Truncate

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

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 Handler

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 to the response body, it should return a status code of 0. This signals to other handlers above it that the response body is already written, and that they should not write to it also.

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 another ServeHTTP method, the returned status code SHOULD be used when writing the response.

If handling errors after calling another 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

type HandlerConfig interface {
	RequestMatcher
	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

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

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

ServeHTTP implements the Handler interface.

type IfMatcher

type IfMatcher struct {
	// contains filtered or unexported fields
}

IfMatcher is a RequestMatcher for 'if' conditions.

func (IfMatcher) And

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

And returns true if all conditions in m are true.

func (IfMatcher) Match

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

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

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

type LogRoller

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

LogRoller implements a type that provides a rolling logger.

func ParseRoller

func ParseRoller(c *caddy.Controller) (*LogRoller, error)

ParseRoller parses roller contents out of c.

func (LogRoller) GetLogWriter

func (l LogRoller) GetLogWriter() io.Writer

GetLogWriter returns an io.Writer that writes to a rolling logger.

type Middleware

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 Path

type Path string

Path represents a URI path.

func (Path) Matches

func (p Path) Matches(other string) bool

Matches checks to see if other matches p.

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

type PathMatcher

type PathMatcher string

PathMatcher is a Path RequestMatcher.

func (PathMatcher) Match

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

Match satisfies RequestMatcher.

type Replacer

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

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

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

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

func MergeRequestMatchers

func MergeRequestMatchers(matchers ...RequestMatcher) RequestMatcher

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

func SetupIfMatcher

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 ResponseRecorder

type ResponseRecorder struct {
	http.ResponseWriter
	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

func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder

NewResponseRecorder 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.

func (*ResponseRecorder) CloseNotify

func (r *ResponseRecorder) CloseNotify() <-chan bool

CloseNotify implements http.CloseNotifier. It just inherits the underlying ResponseWriter's CloseNotify method.

func (*ResponseRecorder) Flush

func (r *ResponseRecorder) Flush()

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

func (*ResponseRecorder) Hijack

func (r *ResponseRecorder) 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 (*ResponseRecorder) Size

func (r *ResponseRecorder) Size() int

Size is a Getter to size property

func (*ResponseRecorder) Status

func (r *ResponseRecorder) Status() int

Status is a Getter to status property

func (*ResponseRecorder) Write

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

func (r *ResponseRecorder) WriteHeader(status int)

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

type Server

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

Server is the HTTP server implementation.

func NewServer

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

func (s *Server) Address() string

Address returns the address s was assigned to listen on.

func (*Server) Listen

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

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

func (*Server) ListenPacket

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

ListenPacket is a noop to implement the Server interface.

func (*Server) OnStartupComplete

func (s *Server) OnStartupComplete()

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

func (*Server) Serve

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

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

func (*Server) ServeHTTP

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

ServeHTTP is the entry point of all HTTP requests.

func (*Server) ServePacket

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

ServePacket is a noop to implement the Server interface.

func (*Server) Stop

func (s *Server) Stop() (err error)

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

type SiteConfig

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

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

	// TLS configuration
	TLS *caddytls.Config

	// 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
	// contains filtered or unexported fields
}

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

func GetConfig

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) AddMiddleware

func (s *SiteConfig) AddMiddleware(m Middleware)

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

func (SiteConfig) Host

func (s SiteConfig) Host() string

Host returns s.Addr.Host.

func (SiteConfig) Middleware

func (s SiteConfig) Middleware() []Middleware

Middleware returns s.middleware (useful for tests).

func (SiteConfig) Port

func (s SiteConfig) Port() string

Port returns s.Addr.Port.

func (SiteConfig) TLSConfig

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

TLSConfig returns s.TLS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL