middleware

package
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2016 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package middleware provides some types and functions common among middleware.

Index

Examples

Constants

This section is empty.

Variables

View Source
var CaseSensitivePath = true

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

View Source
var IndexPages = []string{
	"index.html",
	"index.htm",
	"index.txt",
	"default.html",
	"default.htm",
	"default.txt",
}

IndexPages is a list of pages that may be understood as the "index" files to directories.

Functions

func ContextInclude added in v0.8.3

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 IndexFile added in v0.6.0

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 SetLastModifiedHeader added in v0.8.0

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 SplitCommandAndArgs

func SplitCommandAndArgs(command string) (cmd string, args []string, err error)

SplitCommandAndArgs takes a command string and parses it shell-style into the command and its separate arguments.

Example
var commandLine string
var command string
var args []string

// just for the test - change GOOS and reset it at the end of the test
runtimeGoos = "windows"
defer func() {
	runtimeGoos = runtime.GOOS
}()

commandLine = `mkdir /P "C:\Program Files"`
command, args, _ = SplitCommandAndArgs(commandLine)

fmt.Printf("Windows: %s: %s [%s]\n", commandLine, command, strings.Join(args, ","))

// set GOOS to linux
runtimeGoos = "linux"

commandLine = `mkdir -p /path/with\ space`
command, args, _ = SplitCommandAndArgs(commandLine)

fmt.Printf("Linux: %s: %s [%s]\n", commandLine, command, strings.Join(args, ","))
Output:

Windows: mkdir /P "C:\Program Files": mkdir [/P,C:\Program Files]
Linux: mkdir -p /path/with\ space: mkdir [-p,/path/with space]

Types

type Context added in v0.7.4

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 added in v0.7.4

func (c Context) Cookie(name string) string

Cookie gets the value of a cookie with name name.

func (Context) Header added in v0.7.4

func (c Context) Header(name string) string

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

func (Context) Host added in v0.7.4

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

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

func (Context) IP added in v0.7.4

func (c Context) IP() string

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

func (Context) Include added in v0.7.4

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

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

func (Context) Map added in v0.8.3

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 added in v0.8.2

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 added in v0.7.4

func (c Context) Method() string

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

func (Context) Now added in v0.7.4

func (c Context) Now(format string) string

Now returns the current timestamp in the specified format.

func (Context) NowDate added in v0.7.5

func (c Context) NowDate() time.Time

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

func (Context) PathMatches added in v0.7.4

func (c Context) PathMatches(pattern string) bool

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

func (Context) Port added in v0.7.4

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

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

func (Context) Replace added in v0.7.4

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

Replace replaces instances of find in input with replacement.

func (Context) Slice added in v0.8.3

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

Slice will convert the given arguments into a slice.

func (Context) Split added in v0.8.3

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

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

func (Context) StripExt added in v0.7.6

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 added in v0.7.6

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 added in v0.8.3

func (c Context) ToLower(s string) string

ToLower will convert the given string to lower case.

func (Context) ToUpper added in v0.8.3

func (c Context) ToUpper(s string) string

ToUpper will convert the given string to upper case.

func (Context) Truncate added in v0.7.4

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 added in v0.7.4

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.

func FileServer added in v0.7.6

func FileServer(root http.FileSystem, hide []string) Handler

FileServer implements a production-ready file server and is the 'default' handler for all requests to Caddy. It simply loads and serves the URI requested. If Caddy is run without any extra configuration/directives, this is the only middleware handler that runs. It is not in its own folder like most other middleware handlers because it does not require a directive. It is a special case.

FileServer is adapted from the one in net/http by the Go authors. Significant modifications have been made.

Original license:

Copyright 2009 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

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 LogRoller added in v0.7.6

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

LogRoller implements a middleware that provides a rolling logger.

func (LogRoller) GetLogWriter added in v0.7.6

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, maybe with pattern characters.

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 Replacer added in v0.6.0

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 ResponseRecorder added in v0.8.2

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 added in v0.8.3

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

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

func (*ResponseRecorder) Flush added in v0.8.3

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 added in v0.8.2

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 added in v0.8.2

func (r *ResponseRecorder) Size() int

Size is a Getter to size property

func (*ResponseRecorder) Status added in v0.8.2

func (r *ResponseRecorder) Status() int

Status is a Getter to status property

func (*ResponseRecorder) Write added in v0.8.2

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 added in v0.8.2

func (r *ResponseRecorder) WriteHeader(status int)

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

Directories

Path Synopsis
Package basicauth implements HTTP Basic Authentication.
Package basicauth implements HTTP Basic Authentication.
Package browse provides middleware for listing files in a directory when directory path is requested instead of a specific file.
Package browse provides middleware for listing files in a directory when directory path is requested instead of a specific file.
Package errors implements an HTTP error handling middleware.
Package errors implements an HTTP error handling middleware.
Package extensions contains middleware for clean URLs.
Package extensions contains middleware for clean URLs.
Package fastcgi has middleware that acts as a FastCGI client.
Package fastcgi has middleware that acts as a FastCGI client.
Package gzip provides a simple middleware layer that performs gzip compression on the response.
Package gzip provides a simple middleware layer that performs gzip compression on the response.
Package headers provides middleware that appends headers to requests based on a set of configuration rules that define which routes receive which headers.
Package headers provides middleware that appends headers to requests based on a set of configuration rules that define which routes receive which headers.
Package inner provides a simple middleware that (a) prevents access to internal locations and (b) allows to return files from internal location by setting a special header, e.g.
Package inner provides a simple middleware that (a) prevents access to internal locations and (b) allows to return files from internal location by setting a special header, e.g.
Package log implements request (access) logging middleware.
Package log implements request (access) logging middleware.
Package markdown is middleware to render markdown files as HTML on-the-fly.
Package markdown is middleware to render markdown files as HTML on-the-fly.
Package proxy is middleware that proxies requests.
Package proxy is middleware that proxies requests.
Package redirect is middleware for redirecting certain requests to other locations.
Package redirect is middleware for redirecting certain requests to other locations.
Package rewrite is middleware for rewriting requests internally to a different path.
Package rewrite is middleware for rewriting requests internally to a different path.
Package templates implements template execution for files to be dynamically rendered for the client.
Package templates implements template execution for files to be dynamically rendered for the client.
Package websocket implements a WebSocket server by executing a command and piping its input and output through the WebSocket connection.
Package websocket implements a WebSocket server by executing a command and piping its input and output through the WebSocket connection.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL