Documentation ¶
Overview ¶
Package chi is a small, idiomatic and composable router for building HTTP services.
chi requires Go 1.7 or newer.
Example:
package main import ( "net/http" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" ) func main() { r := chi.NewRouter() r.Use(middleware.Logger) r.Use(middleware.Recoverer) r.Get("/", func(w http.NewResponseWriter, r *http.request) { w.Write([]byte("root.")) }) http.ListenAndServe(":3333", r) }
See github.com/go-chi/chi/_examples/ for more in-depth examples.
Index ¶
- Constants
- Variables
- func DefaultRequestLoggerFactory(r *http.Request, ctx *RouteContext) logging.Logger
- func Header(pairs ...string) (header http.Header)
- func NewLogger(host string) logging.Logger
- func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler
- func SetRouteContextToRequest(r *http.Request, rctx *RouteContext) *http.Request
- func URLParam(r *http.Request, key string) string
- func URLParamFromCtx(ctx context.Context, key string) string
- func URLToString(u *url.URL) string
- func Walk(r Routes, walkFn WalkFunc) error
- type BadPathern
- type BasicWriter
- func (b *BasicWriter) BytesWritten() int
- func (b *BasicWriter) HasStatus(status ...int) bool
- func (b *BasicWriter) Status() int
- func (b *BasicWriter) Tee(w io.Writer)
- func (b *BasicWriter) Unwrap() http.ResponseWriter
- func (b *BasicWriter) Write(buf []byte) (int, error)
- func (b *BasicWriter) WriteHeader(code int)
- type ChainHandler
- func (c *ChainHandler) Middleware() *Middleware
- func (c *ChainHandler) Next(values ...interface{})
- func (c *ChainHandler) Pass()
- func (c *ChainHandler) Request() *http.Request
- func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (c *ChainHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
- func (c *ChainHandler) SetRequest(r *http.Request)
- type ChainRequestSetter
- type ContextHandler
- type ContextHandlerFunc
- type EndpointHandler
- type ErrorHandler
- type FallbackHandlers
- type FlushWriter
- type HTTP2FancyWriter
- type HTTPFancyWriter
- type HTTPHandler
- type HTTPHandlerFunc
- type HTTPHandlerFuncGetter
- type HTTPHandlerGetter
- type Handler
- type HandlerFinder
- type HandlerFunc
- type HandlerInterfaceGetter
- type HttpContextHandler
- type MethodType
- type Middleware
- type Middlewares
- type MiddlewaresStack
- func (stack *MiddlewaresStack) Add(items Middlewares, option int) *MiddlewaresStack
- func (stack *MiddlewaresStack) AddInterface(items []interface{}, option int) *MiddlewaresStack
- func (stack *MiddlewaresStack) All() (items []*Middleware)
- func (stack *MiddlewaresStack) Build() *MiddlewaresStack
- func (stack *MiddlewaresStack) Copy() *MiddlewaresStack
- func (stack *MiddlewaresStack) Has(name ...string) bool
- func (stack *MiddlewaresStack) Override(items Middlewares, option int) *MiddlewaresStack
- type MountHandler
- type Mux
- func (mx *Mux) AcceptMultipartForm(method string) bool
- func (mx *Mux) Api(f func(r Router))
- func (mx *Mux) Arg() interface{}
- func (mx *Mux) ClearArg()
- func (mx *Mux) Connect(pattern string, handler interface{})
- func (mx *Mux) Debug() *Mux
- func (mx *Mux) Delete(pattern string, handler interface{})
- func (mx *Mux) FindHandler(method, path string, header ...http.Header) ContextHandler
- func (mx *Mux) Get(pattern string, handler interface{})
- func (mx *Mux) GetHandlerInterseptor(name string) *Middleware
- func (mx *Mux) GetInterseptor(name string) *Middleware
- func (mx *Mux) GetMiddleware(name string) *Middleware
- func (mx *Mux) GetRouteHandler() ContextHandlerFunc
- func (mx *Mux) Group(fn func(r Router)) Router
- func (mx *Mux) Handle(pattern string, handler interface{})
- func (mx *Mux) HandleFunc(pattern string, handler interface{})
- func (mx *Mux) HandleM(m MethodType, pattern string, handler interface{})
- func (mx *Mux) HandleMethod(method string, pattern string, handler interface{})
- func (mx *Mux) HandlerIntersept(interseptors ...interface{})
- func (mx *Mux) HandlerInterseptOption(option int, interseptors ...interface{})
- func (mx *Mux) Head(pattern string, handler interface{})
- func (mx *Mux) Headers(headers http.Header, f func(r Router))
- func (mx *Mux) Intersept(interseptors ...interface{})
- func (mx *Mux) InterseptErrors() *Mux
- func (mx *Mux) IsArgSet() bool
- func (mx *Mux) IsDebug() bool
- func (mx *Mux) IsInterseptErrors() bool
- func (mx *Mux) LogRequests() *Mux
- func (mx *Mux) Match(rctx *RouteContext, method, path string) bool
- func (mx *Mux) Method(method, pattern string, handler interface{})
- func (mx *Mux) MethodNotAllowed(handler interface{})
- func (mx *Mux) MethodNotAllowedHandler() ContextHandler
- func (mx *Mux) MethodT(method MethodType, pattern string, handler interface{})
- func (mx *Mux) Middlewares() Middlewares
- func (mx *Mux) Mount(pattern string, handler interface{})
- func (mx *Mux) NotFound(handler interface{})
- func (mx *Mux) NotFoundHandler() ContextHandler
- func (mx *Mux) Options(pattern string, handler interface{})
- func (mx *Mux) Overrides(f func(r Router))
- func (mx *Mux) Parent() *Mux
- func (mx *Mux) Patch(pattern string, handler interface{})
- func (mx *Mux) Post(pattern string, handler interface{})
- func (mx *Mux) Prefix() string
- func (mx *Mux) Put(pattern string, handler interface{})
- func (mx *Mux) Route(pattern string, fn func(r Router)) Router
- func (mx *Mux) Routes() []Route
- func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (mx *Mux) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
- func (mx *Mux) SetArg(arg interface{})
- func (mx *Mux) SetDebug(v bool)
- func (mx *Mux) SetInterseptErrors(v bool)
- func (mx *Mux) SetName(name string) *Mux
- func (mx *Mux) SetPrefix(p string)
- func (mx *Mux) SetRouteHandler(handler ContextHandlerFunc)
- func (mx *Mux) Trace(pattern string, handler interface{})
- func (mx *Mux) Use(middlewares ...interface{})
- func (mx *Mux) With(middlewares ...interface{}) Router
- type Options
- type OptionsInterface
- type OrderedMap
- func (p *OrderedMap) Add(key, value string)
- func (p *OrderedMap) AddKey(key string) *OrderedMapKey
- func (p *OrderedMap) AddValue(value string) *OrderedMapValue
- func (p *OrderedMap) Dict() map[string][]string
- func (p *OrderedMap) Get(key string) (value string)
- func (p *OrderedMap) GetValue(key string) *OrderedMapValue
- type OrderedMapKey
- type OrderedMapValue
- type RequestSetter
- type ResponseWriter
- type Route
- type RouteContext
- func GetOrNewRouteContextForRequest(r *http.Request) (*http.Request, *RouteContext)
- func NewRouteContext() *RouteContext
- func NewRouteContextForRequest(r *http.Request) (*http.Request, *RouteContext)
- func RouteContextFromContext(ctx context.Context) *RouteContext
- func RouteContextFromRequest(r *http.Request) *RouteContext
- func (x *RouteContext) Reset()
- func (x *RouteContext) RoutePattern() string
- func (x *RouteContext) Router() Router
- func (x *RouteContext) Routers() []Router
- func (x *RouteContext) SetValue(v interface{}) *RouteContext
- func (x *RouteContext) URLParam(key string) string
- func (x *RouteContext) Value() interface{}
- type RouteContextArgHandler
- type RouteContextFuncHandler
- type RouteContextHandler
- type RouteContextHandlerGetter
- type RouteInterfaceHandler
- type RouteParams
- type Router
- type Routes
- type WalkFunc
- type WrapResponseWriter
Constants ¶
const ( DUPLICATION_OVERRIDE = 0 DUPLICATION_ABORT = 1 DUPLICATION_SKIP = 2 )
const ( SkipErrorInterseption key = iota SkipRequestLogger )
Variables ¶
var ( ErrDuplicateHandler = errors.New("duplicate handler") ErrNoHandlers = errors.New("attempting to route to a mux with no handlers.") )
var (
RequestLoggerFactory = DefaultRequestLoggerFactory
)
var (
// RouteCtxKey is the context.Context key to store the request context.
RouteCtxKey = &contextKey{"RouteContext"}
)
Functions ¶
func DefaultRequestLoggerFactory ¶
func DefaultRequestLoggerFactory(r *http.Request, ctx *RouteContext) logging.Logger
func ServerBaseContext ¶
ServerBaseContext wraps an http.Handler to set the request context to the `baseCtx`.
func SetRouteContextToRequest ¶
func SetRouteContextToRequest(r *http.Request, rctx *RouteContext) *http.Request
func URLParamFromCtx ¶
URLParamFromCtx returns the url parameter from a http.request Context.
func URLToString ¶
Types ¶
type BadPathern ¶
type BadPathern struct {
// contains filtered or unexported fields
}
func (BadPathern) Error ¶
func (this BadPathern) Error() string
type BasicWriter ¶
type BasicWriter struct { http.ResponseWriter // contains filtered or unexported fields }
BasicWriter wraps a http.NewResponseWriter that implements the minimal http.NewResponseWriter interface.
func (*BasicWriter) BytesWritten ¶
func (b *BasicWriter) BytesWritten() int
func (*BasicWriter) HasStatus ¶
func (b *BasicWriter) HasStatus(status ...int) bool
func (*BasicWriter) Status ¶
func (b *BasicWriter) Status() int
func (*BasicWriter) Tee ¶
func (b *BasicWriter) Tee(w io.Writer)
func (*BasicWriter) Unwrap ¶
func (b *BasicWriter) Unwrap() http.ResponseWriter
func (*BasicWriter) WriteHeader ¶
func (b *BasicWriter) WriteHeader(code int)
type ChainHandler ¶
type ChainHandler struct { Middlewares Middlewares Endpoint ContextHandler Index int Writer ResponseWriter Context *RouteContext // contains filtered or unexported fields }
ChainHandler is a http.Handler with support for handler composition and execution.
func (*ChainHandler) Middleware ¶
func (c *ChainHandler) Middleware() *Middleware
func (*ChainHandler) Next ¶
func (c *ChainHandler) Next(values ...interface{})
func (*ChainHandler) Pass ¶
func (c *ChainHandler) Pass()
func (*ChainHandler) Request ¶
func (c *ChainHandler) Request() *http.Request
func (*ChainHandler) ServeHTTP ¶
func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*ChainHandler) ServeHTTPContext ¶
func (c *ChainHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
func (*ChainHandler) SetRequest ¶
func (c *ChainHandler) SetRequest(r *http.Request)
type ChainRequestSetter ¶
type ChainRequestSetter interface {
SetRequest(chain *ChainHandler, r *http.Request)
}
func NewChainRequestSetter ¶
func NewChainRequestSetter(setter func(chain *ChainHandler, r *http.Request)) ChainRequestSetter
type ContextHandler ¶
type ContextHandler interface {
ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
}
func Fallback ¶
func Fallback(handlers ...ContextHandler) ContextHandler
func NewContextHandler ¶
func NewContextHandler(f func(w http.ResponseWriter, r *http.Request, rctx *RouteContext)) ContextHandler
func NotFoundHandler ¶
func NotFoundHandler() ContextHandler
type ContextHandlerFunc ¶
type ContextHandlerFunc func(handler ContextHandler, w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type EndpointHandler ¶
type EndpointHandler struct {
// contains filtered or unexported fields
}
func (EndpointHandler) Handler ¶
func (ep EndpointHandler) Handler(headers ...http.Header) ContextHandler
func (EndpointHandler) HasHandler ¶
func (ep EndpointHandler) HasHandler() bool
func (EndpointHandler) ServeHTTP ¶
func (eh EndpointHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (EndpointHandler) ServeHTTPContext ¶
func (eh EndpointHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type ErrorHandler ¶
type ErrorHandler func(URL *url.URL, debug bool, w ResponseWriter, r *http.Request, context *RouteContext, begin time.Time, err interface{})
type FallbackHandlers ¶
type FallbackHandlers []ContextHandler
func (*FallbackHandlers) Add ¶
func (this *FallbackHandlers) Add(handler ...ContextHandler)
func (FallbackHandlers) ServeHTTP ¶
func (this FallbackHandlers) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (FallbackHandlers) ServeHTTPContext ¶
func (this FallbackHandlers) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type FlushWriter ¶
type FlushWriter struct {
BasicWriter
}
func (*FlushWriter) Flush ¶
func (f *FlushWriter) Flush()
type HTTP2FancyWriter ¶
type HTTP2FancyWriter struct {
BasicWriter
}
HTTP2FancyWriter is a HTTP2 writer that additionally satisfies http.CloseNotifier, http.Flusher, and io.ReaderFrom. It exists for the common case of wrapping the http.NewResponseWriter that package http gives you, in order to make the proxied object support the full method set of the proxied object.
func (*HTTP2FancyWriter) CloseNotify ¶
func (f *HTTP2FancyWriter) CloseNotify() <-chan bool
func (*HTTP2FancyWriter) Flush ¶
func (f *HTTP2FancyWriter) Flush()
type HTTPFancyWriter ¶
type HTTPFancyWriter struct {
BasicWriter
}
HTTPFancyWriter is a HTTP writer that additionally satisfies http.CloseNotifier, http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case of wrapping the http.NewResponseWriter that package http gives you, in order to make the proxied object support the full method set of the proxied object.
func (*HTTPFancyWriter) CloseNotify ¶
func (f *HTTPFancyWriter) CloseNotify() <-chan bool
func (*HTTPFancyWriter) Flush ¶
func (f *HTTPFancyWriter) Flush()
func (*HTTPFancyWriter) Hijack ¶
func (f *HTTPFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
type HTTPHandler ¶
func (*HTTPHandler) Handler ¶
func (h *HTTPHandler) Handler() http.Handler
func (*HTTPHandler) ServeHTTPContext ¶
func (h *HTTPHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type HTTPHandlerFunc ¶
type HTTPHandlerFunc struct {
Value func(http.ResponseWriter, *http.Request)
}
func (*HTTPHandlerFunc) Handler ¶
func (h *HTTPHandlerFunc) Handler() http.HandlerFunc
func (*HTTPHandlerFunc) ServeHTTP ¶
func (h *HTTPHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*HTTPHandlerFunc) ServeHTTPContext ¶
func (h *HTTPHandlerFunc) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type HTTPHandlerFuncGetter ¶
type HTTPHandlerFuncGetter interface {
Handler() http.HandlerFunc
}
type HTTPHandlerGetter ¶
type Handler ¶
type Handler interface { http.Handler ContextHandler }
func HttpHandler ¶
func HttpHandler(handler interface{}) (h Handler)
type HandlerFinder ¶
type HandlerFinder interface {
FindHandler(method, path string, header ...http.Header) ContextHandler
}
type HandlerFunc ¶
type HandlerFunc func(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type HandlerInterfaceGetter ¶
type HandlerInterfaceGetter interface {
Handler() interface{}
}
type HttpContextHandler ¶
type HttpContextHandler struct { ContextHandler http.Handler }
type MethodType ¶
type MethodType int
const ( STUB MethodType = 1 << iota CONNECT DELETE GET HEAD OPTIONS PATCH POST PUT TRACE )
func RegisterMethod ¶
func RegisterMethod(method string) MethodType
func (MethodType) String ¶
func (mt MethodType) String() string
type Middleware ¶
type Middleware struct { Name string Handler func(chain *ChainHandler) Before []string After []string }
func NewMiddleware ¶
func NewMiddleware(f interface{}) *Middleware
type Middlewares ¶
type Middlewares []*Middleware
Middlewares type is a slice of standard middleware handlers with methods to compose middleware chains and interface{}'s.
func Chain ¶
func Chain(middlewares ...*Middleware) Middlewares
Chain returns a Middlewares type from a slice of middleware handlers.
func (*Middlewares) Add ¶
func (this *Middlewares) Add(md ...*Middleware)
func (Middlewares) Handler ¶
func (mws Middlewares) Handler(h interface{}) Handler
Handler builds and returns a http.Handler from the chain of middlewares, with `h http.Handler` as the final handler.
type MiddlewaresStack ¶
type MiddlewaresStack struct { Name string ByName map[string]*Middleware Items Middlewares Anonymous Middlewares Len int // contains filtered or unexported fields }
func NewMiddlewaresStack ¶
func NewMiddlewaresStack(name string, acceptAnonymous bool) *MiddlewaresStack
func (*MiddlewaresStack) Add ¶
func (stack *MiddlewaresStack) Add(items Middlewares, option int) *MiddlewaresStack
func (*MiddlewaresStack) AddInterface ¶
func (stack *MiddlewaresStack) AddInterface(items []interface{}, option int) *MiddlewaresStack
func (*MiddlewaresStack) All ¶
func (stack *MiddlewaresStack) All() (items []*Middleware)
func (*MiddlewaresStack) Build ¶
func (stack *MiddlewaresStack) Build() *MiddlewaresStack
func (*MiddlewaresStack) Copy ¶
func (stack *MiddlewaresStack) Copy() *MiddlewaresStack
func (*MiddlewaresStack) Has ¶
func (stack *MiddlewaresStack) Has(name ...string) bool
func (*MiddlewaresStack) Override ¶
func (stack *MiddlewaresStack) Override(items Middlewares, option int) *MiddlewaresStack
type MountHandler ¶
type MountHandler struct { Handler interface{} // contains filtered or unexported fields }
func (*MountHandler) ServeHTTPContext ¶
func (h *MountHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, context *RouteContext)
type Mux ¶
Mux is a simple HTTP route multiplexer that parses a request path, records any URL params, and executes an end handler. It implements the http.Handler interface and is friendly with the standard library.
Mux is designed to be fast, minimal and offer a powerful API for building modular and composable HTTP services with a large set of handlers. It's particularly useful for writing large REST API services that break a handler into many smaller parts composed of middlewares and end handlers.
func NewRouter ¶
func NewRouter() *Mux
NewRouter returns a new Mux object that implements the Router interface.
func (*Mux) AcceptMultipartForm ¶
func (*Mux) Connect ¶
Connect adds the route `pattern` that matches a CONNECT http method to execute the `handler` Handler.
func (*Mux) Delete ¶
Delete adds the route `pattern` that matches a DELETE http method to execute the `handler` Handler.
func (*Mux) FindHandler ¶
func (mx *Mux) FindHandler(method, path string, header ...http.Header) ContextHandler
func (*Mux) Get ¶
Get adds the route `pattern` that matches a GET http method to execute the `handler` Handler.
func (*Mux) GetHandlerInterseptor ¶
func (mx *Mux) GetHandlerInterseptor(name string) *Middleware
func (*Mux) GetInterseptor ¶
func (mx *Mux) GetInterseptor(name string) *Middleware
func (*Mux) GetMiddleware ¶
func (mx *Mux) GetMiddleware(name string) *Middleware
func (*Mux) GetRouteHandler ¶
func (mx *Mux) GetRouteHandler() ContextHandlerFunc
func (*Mux) Group ¶
Group creates a new inline-Mux with a fresh middleware stack. It's useful for a group of handlers along the same routing path that use an additional set of middlewares. See _examples/.
func (*Mux) Handle ¶
Handle adds the route `pattern` that matches any http method to execute the `handler` Handler.
func (*Mux) HandleFunc ¶
HandleFunc adds the route `pattern` that matches any http method to execute the `handler` HandlerFunc.
func (*Mux) HandleM ¶
func (mx *Mux) HandleM(m MethodType, pattern string, handler interface{})
HandleM registers a http.Handler in the routing tree for a particular http method and routing pattern.
func (*Mux) HandleMethod ¶
handle registers a http.Handler in the routing tree for a particular http method and routing pattern.
func (*Mux) HandlerIntersept ¶
func (mx *Mux) HandlerIntersept(interseptors ...interface{})
Use appends a middleware handler to the Mux middleware stack.
The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next Handler.
func (*Mux) HandlerInterseptOption ¶
func (*Mux) Head ¶
Head adds the route `pattern` that matches a HEAD http method to execute the `handler` Handler.
func (*Mux) Intersept ¶
func (mx *Mux) Intersept(interseptors ...interface{})
Use appends a middleware handler to the Mux middleware stack.
The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next Handler.
func (*Mux) InterseptErrors ¶
func (*Mux) IsInterseptErrors ¶
func (*Mux) LogRequests ¶
func (*Mux) Match ¶
func (mx *Mux) Match(rctx *RouteContext, method, path string) bool
Match searches the routing tree for a handler that matches the method/path. It's similar to routing a http request, but without executing the handler thereafter.
Note: the *Context state is updated during execution, so manage the state carefully or make a NewRouteContext().
func (*Mux) Method ¶
Method adds the route `pattern` that matches `method` http method to execute the `handler` Handler.
func (*Mux) MethodNotAllowed ¶
func (mx *Mux) MethodNotAllowed(handler interface{})
MethodNotAllowed sets a custom Handler for routing paths where the method is unresolved. The default handler returns a 405 with an empty body.
func (*Mux) MethodNotAllowedHandler ¶
func (mx *Mux) MethodNotAllowedHandler() ContextHandler
MethodNotAllowedHandler returns the default Mux 405 responder whenever a method cannot be resolved for a route.
func (*Mux) MethodT ¶
func (mx *Mux) MethodT(method MethodType, pattern string, handler interface{})
HandleMethod adds the route `pattern` that matches `method` http method to execute the `handler` Handler.
func (*Mux) Middlewares ¶
func (mx *Mux) Middlewares() Middlewares
Middlewares returns a slice of middleware handler functions.
func (*Mux) Mount ¶
Mount attaches another Handler or chi Router as a subrouter along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount. See _examples/.
Note that Mount() simply sets a wildcard along the `pattern` that will continue routing at the `handler`, which in most cases is another chi.Router. As a result, if you define two Mount() routes on the exact same pattern the mount will panic.
func (*Mux) NotFound ¶
func (mx *Mux) NotFound(handler interface{})
NotFound sets a custom Handler for routing paths that could not be found. The default 404 handler is `http.NotFound`.
func (*Mux) NotFoundHandler ¶
func (mx *Mux) NotFoundHandler() ContextHandler
NotFoundHandler returns the default Mux 404 responder whenever a route cannot be found.
func (*Mux) Options ¶
Options adds the route `pattern` that matches a OPTIONS http method to execute the `handler` Handler.
func (*Mux) Patch ¶
Patch adds the route `pattern` that matches a PATCH http method to execute the `handler` Handler.
func (*Mux) Post ¶
Post adds the route `pattern` that matches a POST http method to execute the `handler` Handler.
func (*Mux) Put ¶
Put adds the route `pattern` that matches a PUT http method to execute the `handler` Handler.
func (*Mux) Route ¶
Route creates a new Mux with a fresh middleware stack and mounts it along the `pattern` as a subrouter. Effectively, this is a short-hand call to Mount. See _examples/.
func (*Mux) Routes ¶
Routes returns a slice of routing information from the tree, useful for traversing available routes of a router.
func (*Mux) ServeHTTP ¶
func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the single method of the http.Handler interface that makes Mux interoperable with the standard library. It uses a sync.Pool to get and reuse routing contexts for each request.
func (*Mux) ServeHTTPContext ¶
func (mx *Mux) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
func (*Mux) SetInterseptErrors ¶
func (*Mux) SetRouteHandler ¶
func (mx *Mux) SetRouteHandler(handler ContextHandlerFunc)
func (*Mux) Trace ¶
Trace adds the route `pattern` that matches a TRACE http method to execute the `handler` Handler.
func (*Mux) Use ¶
func (mx *Mux) Use(middlewares ...interface{})
Use appends a middleware handler to the Mux middleware stack.
The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next Handler.
type Options ¶
type Options map[interface{}]interface{}
func NewOptions ¶
func NewOptions(data ...map[interface{}]interface{}) Options
type OptionsInterface ¶
type OrderedMap ¶
type OrderedMap struct { Keys []*string Values []*OrderedMapValue Map map[string]*OrderedMapKey Size int }
func NewOrderedMap ¶
func NewOrderedMap() *OrderedMap
func (*OrderedMap) Add ¶
func (p *OrderedMap) Add(key, value string)
func (*OrderedMap) AddKey ¶
func (p *OrderedMap) AddKey(key string) *OrderedMapKey
func (*OrderedMap) AddValue ¶
func (p *OrderedMap) AddValue(value string) *OrderedMapValue
func (*OrderedMap) Dict ¶
func (p *OrderedMap) Dict() map[string][]string
func (*OrderedMap) Get ¶
func (p *OrderedMap) Get(key string) (value string)
func (*OrderedMap) GetValue ¶
func (p *OrderedMap) GetValue(key string) *OrderedMapValue
type OrderedMapKey ¶
type OrderedMapKey struct { Index int Key *string Values []*OrderedMapValue }
type OrderedMapValue ¶
type RequestSetter ¶
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter // Status returns the HTTP status of the request, or 0 if one has not // yet been sent. Status() int // BytesWritten returns the total number of bytes sent to the client. BytesWritten() int HasStatus(status ...int) bool }
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) ResponseWriter
type Route ¶
type Route struct { Pattern string Handlers map[string]ContextHandler SubRoutes Routes }
Route describes the details of a routing handler.
type RouteContext ¶
type RouteContext struct { Routes Routes // Routing path/method override used during the route search. // See Mux#routeHTTP method. RoutePath string RouteMethod string // Routing pattern stack throughout the lifecycle of the request, // across all connected routers. It is a record of all matching // patterns across a stack of Sub-routers. RoutePatterns []string // URLParams are the stack of routeParams captured during the // routing lifecycle across a stack of Sub-routers. URLParams *OrderedMap DefaultValueKey interface{} Data map[interface{}]interface{} RequestSetters map[interface{}]RequestSetter ChainRequestSetters map[interface{}]ChainRequestSetter Handler interface{} RouterStack []Router Log logging.Logger ApiExt string // contains filtered or unexported fields }
Context is the default routing context set on the root node of a request context to track route patterns, URL parameters and an optional routing path.
func GetOrNewRouteContextForRequest ¶
func GetOrNewRouteContextForRequest(r *http.Request) (*http.Request, *RouteContext)
func NewRouteContext ¶
func NewRouteContext() *RouteContext
NewRouteContext returns a new routing Context object.
func NewRouteContextForRequest ¶
func NewRouteContextForRequest(r *http.Request) (*http.Request, *RouteContext)
func RouteContextFromContext ¶
func RouteContextFromContext(ctx context.Context) *RouteContext
RouteContext returns chi's routing Context object from a http.request Context.
func RouteContextFromRequest ¶
func RouteContextFromRequest(r *http.Request) *RouteContext
RouteContext returns chi's routing Context object from a http.request Context.
func (*RouteContext) Reset ¶
func (x *RouteContext) Reset()
Reset a routing context to its initial state.
func (*RouteContext) RoutePattern ¶
func (x *RouteContext) RoutePattern() string
RoutePattern builds the routing pattern string for the particular request, at the particular point during routing. This means, the value will change throughout the execution of a request in a router. That is why its advised to only use this value after calling the next handler.
For example,
func Instrument(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.NewResponseWriter, r *http.request) { next.ServeHTTP(w, r) routePattern := chi.RouteContext(r.Context()).RoutePattern() measure(w, r, routePattern) }) }
func (*RouteContext) Router ¶
func (x *RouteContext) Router() Router
func (*RouteContext) Routers ¶
func (x *RouteContext) Routers() []Router
func (*RouteContext) SetValue ¶
func (x *RouteContext) SetValue(v interface{}) *RouteContext
func (*RouteContext) URLParam ¶
func (x *RouteContext) URLParam(key string) string
URLParam returns the corresponding URL parameter value from the request routing context.
func (*RouteContext) Value ¶
func (x *RouteContext) Value() interface{}
type RouteContextArgHandler ¶
type RouteContextArgHandler struct {
Value func(*RouteContext)
}
func (*RouteContextArgHandler) Handler ¶
func (h *RouteContextArgHandler) Handler() interface{}
func (*RouteContextArgHandler) ServeHTTP ¶
func (h *RouteContextArgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*RouteContextArgHandler) ServeHTTPContext ¶
func (h *RouteContextArgHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type RouteContextFuncHandler ¶
type RouteContextFuncHandler struct {
Value func(http.ResponseWriter, *http.Request, *RouteContext)
}
func (*RouteContextFuncHandler) Handler ¶
func (h *RouteContextFuncHandler) Handler() HandlerFunc
func (*RouteContextFuncHandler) ServeHTTP ¶
func (h *RouteContextFuncHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*RouteContextFuncHandler) ServeHTTPContext ¶
func (h *RouteContextFuncHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type RouteContextHandler ¶
type RouteContextHandler interface {
Handler() HandlerFunc
}
type RouteContextHandlerGetter ¶
type RouteContextHandlerGetter interface {
Handler() HandlerFunc
}
type RouteInterfaceHandler ¶
type RouteInterfaceHandler struct {
Value func(interface{})
}
func (*RouteInterfaceHandler) Handler ¶
func (h *RouteInterfaceHandler) Handler() interface{}
func (*RouteInterfaceHandler) ServeHTTP ¶
func (h *RouteInterfaceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*RouteInterfaceHandler) ServeHTTPContext ¶
func (h *RouteInterfaceHandler) ServeHTTPContext(w http.ResponseWriter, r *http.Request, rctx *RouteContext)
type RouteParams ¶
type RouteParams struct {
Keys, Values []string
}
RouteParams is a structure to track URL routing parameters efficiently.
func (*RouteParams) Add ¶
func (s *RouteParams) Add(key, value string)
Add will append a URL parameter to the end of the route param
type Router ¶
type Router interface { Handler Routes HandlerFinder Prefix() string SetPrefix(p string) SetRouteHandler(handler ContextHandlerFunc) GetRouteHandler() ContextHandlerFunc IsArgSet() bool SetArg(arg interface{}) Arg() interface{} ClearArg() Intersept(interseptors ...interface{}) GetInterseptor(name string) *Middleware HandlerIntersept(interseptors ...interface{}) GetHandlerInterseptor(name string) *Middleware // Use appends one of more middlewares onto the Router stack. Use(middlewares ...interface{}) // Return middleware by name or `nil` GetMiddleware(name string) *Middleware // With adds inline middlewares for an endpoint handler. With(middlewares ...interface{}) Router // Group adds a new inline-Router along the current routing // path, with a fresh middleware stack for the inline-Router. Group(fn func(r Router)) Router // Route mounts a Sub-Router along a `pattern` string. Route(pattern string, fn func(r Router)) Router // Mount attaches another interface{} along ./pattern/* Mount(pattern string, h interface{}) // Handle and HandleFunc adds routes for `pattern` that matches // all HTTP methods. Handle(pattern string, h interface{}) // Method and add routes for `pattern` that matches // the `method` HTTP method. Method(method, pattern string, h interface{}) // MethodT adds the route `pattern` that matches `method` http method to // execute the `handler` Handler. MethodT(method MethodType, pattern string, handler interface{}) // HTTP-method routing along `pattern` HandleMethod(method string, pattern string, handler interface{}) HandleM(method MethodType, pattern string, handler interface{}) Connect(pattern string, h interface{}) Delete(pattern string, h interface{}) Get(pattern string, h interface{}) Head(pattern string, h interface{}) Options(pattern string, h interface{}) Patch(pattern string, h interface{}) Post(pattern string, h interface{}) Put(pattern string, h interface{}) Trace(pattern string, h interface{}) Headers(headers http.Header, f func(r Router)) Api(f func(r Router)) // NotFound defines a handler to respond whenever a route could // not be found. NotFound(h interface{}) // MethodNotAllowed defines a handler to respond whenever a method is // not allowed. MethodNotAllowed(h interface{}) Overrides(f func(r Router)) }
Router consisting of the core routing methods used by chi's Mux, using only the standard net/http.
type Routes ¶
type Routes interface { // Routes returns the routing tree in an easily traversable structure. Routes() []Route // Middlewares returns the list of middlewares in use by the router. Middlewares() Middlewares // Match searches the routing tree for a handler that matches // the method/path - similar to routing a http request, but without // executing the handler thereafter. Match(rctx *RouteContext, method, path string) bool }
Routes interface adds two methods for router traversal, which is also used by the `docgen` subpackage to generation documentation for Routers.
type WalkFunc ¶
type WalkFunc func(method string, route string, handler ContextHandler, middlewares ...*Middleware) error
WalkFunc is the type of the function called for each method and route visited by Walk.
type WrapResponseWriter ¶
type WrapResponseWriter interface { ResponseWriter // Tee causes the response body to be written to the given io.Writer in // addition to proxying the writes through. Only one io.Writer can be // tee'd to at once: setting a second one will overwrite the first. // Writes will be sent to the proxy before being written to this // io.Writer. It is illegal for the tee'd writer to be modified // concurrently with writes. Tee(io.Writer) // Unwrap returns the original proxied target. Unwrap() http.ResponseWriter }
WrapResponseWriter is a proxy around an http.NewResponseWriter that allows you to hook into various parts of the response process.