Documentation ¶
Overview ¶
Package middleware contains several middlewares for bowtie.
See https://github.com/mtabini/go-bowtie for more information.
Index ¶
- Variables
- func CleanPath(p string) string
- func ErrorReporter(c bowtie.Context, next func())
- func NewLogger(logger Logger) bowtie.Middleware
- func Recovery(c bowtie.Context, next func())
- func RouterContextFactory(context bowtie.Context)
- type CORSHandler
- type Handle
- type HandleList
- type Logger
- type Param
- type Params
- type Router
- func (r *Router) ContextFactory() bowtie.ContextFactory
- func (r *Router) DELETE(path string, handles ...Handle)
- func (r *Router) GET(path string, handles ...Handle)
- func (r *Router) GetSupportedMethods(path string) []string
- func (r *Router) HEAD(path string, handles ...Handle)
- func (r *Router) Handle(method, path string, handles HandleList)
- func (r *Router) Middleware() bowtie.Middleware
- func (r *Router) PATCH(path string, handles ...Handle)
- func (r *Router) POST(path string, handles ...Handle)
- func (r *Router) PUT(path string, handles ...Handle)
- func (r *Router) Serve(c bowtie.Context, next func())
Constants ¶
This section is empty.
Variables ¶
var RouterParamsKey = bowtie.GenerateContextKey()
Functions ¶
func CleanPath ¶
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
func ErrorReporter ¶
func ErrorReporter(c bowtie.Context, next func())
ErrorReporter is a middleware that safely handles error reporting by outputting the errors that have accumulated in the context's response writer. It computes the status of a request from the maximum response status of all the errors (if any are present).
func NewLogger ¶
func NewLogger(logger Logger) bowtie.Middleware
NewLogger creates a new logger middleware. It waits until all other middlewares have finished running, then calls `logger` with the request's context.
func Recovery ¶
func Recovery(c bowtie.Context, next func())
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. While Martini is in development mode, Recovery will also output the panic as HTML.
Borrowed from https://github.com/go-martini/martini/blob/master/recovery.go
func RouterContextFactory ¶
func RouterContextFactory(context bowtie.Context)
Types ¶
type CORSHandler ¶
type CORSHandler struct { AllowedOrigins []string AllowedHeaders []string ExposedHeaders []string // contains filtered or unexported fields }
Struct CORSHandler provides CORS support. It can automatically use an instance of Router to provide accurate responses to an OPTION preflight request, and supports restricting which headers are allowed in input and output.
CORSHandler conforms to the bowtie.MiddlewareProvided interface.
A set of sensible defaults can be installed by calling the SetDefaults() method.
func NewCORSHandler ¶
func NewCORSHandler(router *Router) *CORSHandler
NewCORSHandler creates a new CORS Handler that uses `router` to determine which HTTP methods are acceptable for a given route.
func (*CORSHandler) ContextFactory ¶
func (h *CORSHandler) ContextFactory() bowtie.ContextFactory
func (*CORSHandler) Middleware ¶
func (h *CORSHandler) Middleware() bowtie.Middleware
func (*CORSHandler) SetDefaults ¶
func (c *CORSHandler) SetDefaults()
SetDefaults sets a basic set of defaults. Allows any origin and exposes commonly-used headers both in input and output
type Handle ¶
type Handle func(c bowtie.Context)
Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
type HandleList ¶
type HandleList []Handle
type Logger ¶
type Logger func(c bowtie.Context)
Logger is a generic logger function that takes a bowtie context and is tasked with logging the request it encapsulates. You pass this value to NewLogger and then add the resulting middleware to your server.
The logger middleware comes with two output handlers: plaintext and Bunyan. For example:
s := bowtie.NewServer() s.AddMiddleware(middleware.NewLogger(middleware.MakePlaintextLogger()))
func MakeBunyanLogger ¶
func MakeBunyanLogger(logger *bunyan.Logger) Logger
BunyanLogger logs requests using a Bunyan logger. See https://github.com/mtabini/go-bunyan for more information
func MakePlaintextLogger ¶
func MakePlaintextLogger() Logger
MakePlaintextLogger logs requests to standard output using this space-limited simple format: RemoteAddress Method URL Status RunningTime
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
type Router ¶
type Router struct { // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // contains filtered or unexported fields }
Original Copyright 2013 Julien Schmidt. All rights reserved. Modified by Marco Tabini 2015 Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
httprouter's original code can be found at https://github.com/julienschmidt/httprouter
The router matches incoming requests by the request method and the path. If a handle is registered for this path and method, the router delegates the request to that function. For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to register handles, for all other methods router.Handle can be used.
The registered path, against which the router matches incoming requests, can contain two types of parameters:
Syntax Type :name named parameter *name catch-all parameter
Named parameters are dynamic path segments. They match anything until the next '/' or the path end:
Path: /blog/:category/:post Requests: /blog/go/request-routers match: category="go", post="request-routers" /blog/go/request-routers/ no match, but the router would redirect /blog/go/ no match /blog/go/request-routers/comments no match
Catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all paramerters must always be the final path element.
Path: /files/*filepath Requests: /files/ match: filepath="/" /files/LICENSE match: filepath="/LICENSE" /files/templates/article.html match: filepath="/templates/article.html" /files no match, but the router would redirect
The value of parameters is saved as a slice of the Param struct, consisting each of a key and a value. The slice is passed to the Handle func as part of an extension to the built-in bowtie context.
There are two ways to retrieve the value of a parameter; if c is the context passed to the handler:
ps := c.(RouterContext).Params() // by the name of the parameter user := ps.ByName("user") // defined by :user or *user // by the index of the parameter. This way you can also get the name (key) thirdKey := ps[2].Key // the name of the 3rd parameter thirdValue := ps[2].Value // the value of the 3rd parameter
func NewRouter ¶
func NewRouter() *Router
New returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.
func (*Router) ContextFactory ¶
func (r *Router) ContextFactory() bowtie.ContextFactory
func (*Router) GetSupportedMethods ¶
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, handles HandleList)
Handle registers a new request handle with the given path and method.
For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
func (*Router) Middleware ¶
func (r *Router) Middleware() bowtie.Middleware