Document methods

This commit is contained in:
Peter Kieltyka 2016-04-03 11:56:35 -04:00
parent 1f4f1dfb3c
commit 3031602cdf
12 changed files with 109 additions and 40 deletions

View file

@ -1,4 +1,4 @@
Copyright (c) 2015-2016 Peter Kieltyka (https://twitter.com/peterk)
Copyright (c) 2015-2016 Peter Kieltyka (https://github.com/pkieltyka)
MIT License

16
chi.go
View file

@ -6,12 +6,19 @@ import (
"golang.org/x/net/context"
)
// Create a new mux that adheres to Router interface, with an optional
// parent context to signal server context to all requests.
// NewRouter returns a new Mux object that implements the Router interface.
// It accepts an optional parent context.Context argument used by all
// request contexts useful for signaling a server shutdown.
func NewRouter(parent ...context.Context) *Mux {
return NewMux(parent...)
}
// A Router consisting of the core routing methods used by chi's Mux.
//
// NOTE, the plan: hopefully once net/context makes it into the stdlib and
// net/http supports a request context, we will remove the chi.Handler
// interface, and the Router argument types will be http.Handler instead
// of interface{}.
type Router interface {
http.Handler
Handler
@ -35,11 +42,6 @@ type Router interface {
Options(pattern string, handlers ...interface{})
}
// NOTE, the plan: hopefully once net/context makes it into the stdlib and
// net/http supports a request context, we will remove the chi.Handler
// interface, and the Router argument types will be http.Handler instead
// of interface{}.
// Handler is like net/http's http.Handler, but also includes a
// mechanism for serving requests with a context.
type Handler interface {

View file

@ -10,6 +10,8 @@ const (
routeCtxKey ctxKey = iota
)
// A Context is the default routing context set on the root node of a
// request context to track URL parameters and an optional routing path.
type Context struct {
context.Context
@ -20,6 +22,7 @@ type Context struct {
RoutePath string
}
// neContext returns a new routing context object.
func newContext(parent context.Context) *Context {
rctx := &Context{}
ctx := context.WithValue(parent, routeCtxKey, rctx)
@ -27,6 +30,7 @@ func newContext(parent context.Context) *Context {
return rctx
}
// reset a routing context to its initial state.
func (x *Context) reset() {
x.Params = x.Params[:0]
x.RoutePath = ""

View file

@ -7,8 +7,8 @@ import (
"golang.org/x/net/context"
)
// 499 Client Closed Request (Nginx)
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
// StatusClientClosedRequest represents a 499 Client Closed Request (Nginx) HTTP status.
// See: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
const StatusClientClosedRequest = 499
// CloseNotify is a middleware that cancels ctx when the underlying

View file

@ -36,7 +36,7 @@ func DefaultCompress(next http.Handler) http.Handler {
return Compress(flate.DefaultCompression)(next)
}
// CompressLevel is a middleware that compresses response
// Compress is a middleware that compresses response
// body of a given content types to a data format based
// on Accept-Encoding request header. It uses a given
// compression level.

View file

@ -10,6 +10,15 @@ import (
"golang.org/x/net/context"
)
// Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
//
// func MyService() http.Handler {
// r := chi.NewRouter()
// // ..middlewares
// r.Mount("/debug", profiler.Router())
// // ..routes
// return r
// }
func Profiler() http.Handler {
r := chi.NewRouter()
r.Use(NoCache)

View file

@ -19,6 +19,7 @@ import (
// Key to use when setting the request ID.
type ctxKeyRequestID int
// RequestIDKey is the key that holds th unique request ID in a request context.
const RequestIDKey ctxKeyRequestID = 0
var prefix string

62
mux.go
View file

@ -10,15 +10,23 @@ import (
var _ Router = &Mux{}
// A 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 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.
type Mux struct {
// Parent context for the server
// A parent root context for any request that is usually a server context
parentCtx context.Context
// The middleware stack, supporting..
// func(http.Handler) http.Handler and func(chi.Handler) chi.Handler
middlewares []interface{}
// The radix trie router with URL parameter matching
// The radix trie router
router *treeRouter
// The mux handler, chained middleware stack and tree router
@ -61,6 +69,7 @@ var methodMap = map[string]methodTyp{
"TRACE": mTRACE,
}
// NewMux returns a new Mux object with an optional parent context.
func NewMux(parent ...context.Context) *Mux {
pctx := context.Background()
if len(parent) > 0 {
@ -75,59 +84,80 @@ func NewMux(parent ...context.Context) *Mux {
return mux
}
// Append to the middleware stack
// Use appends a middleware handler to the Mux middleware stack.
func (mx *Mux) Use(mws ...interface{}) {
for _, mw := range mws {
mx.middlewares = append(mx.middlewares, assertMiddleware(mw))
}
}
// Handle adds a route for all http methods that match the `pattern`
// for the `handlers` chain.
func (mx *Mux) Handle(pattern string, handlers ...interface{}) {
mx.handle(mALL, pattern, handlers...)
}
// Connect adds a route that matches a CONNECT http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Connect(pattern string, handlers ...interface{}) {
mx.handle(mCONNECT, pattern, handlers...)
}
// Head adds a route that matches a HEAD http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Head(pattern string, handlers ...interface{}) {
mx.handle(mHEAD, pattern, handlers...)
}
// Get adds a route that matches a GET http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Get(pattern string, handlers ...interface{}) {
mx.handle(mGET, pattern, handlers...)
}
// Post adds a route that matches a POST http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Post(pattern string, handlers ...interface{}) {
mx.handle(mPOST, pattern, handlers...)
}
// Put adds a route that matches a PUT http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Put(pattern string, handlers ...interface{}) {
mx.handle(mPUT, pattern, handlers...)
}
// Patch adds a route that matches a PATCH http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Patch(pattern string, handlers ...interface{}) {
mx.handle(mPATCH, pattern, handlers...)
}
// Delete adds a route that matches a DELETE http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Delete(pattern string, handlers ...interface{}) {
mx.handle(mDELETE, pattern, handlers...)
}
// Trace adds a route that matches a TRACE http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Trace(pattern string, handlers ...interface{}) {
mx.handle(mTRACE, pattern, handlers...)
}
// Options adds a route that matches a OPTIONS http method and the `pattern`
// for the `handlers` chain.
func (mx *Mux) Options(pattern string, handlers ...interface{}) {
mx.handle(mOPTIONS, pattern, handlers...)
}
// NotFound sets a custom handler for the case when no routes match
// NotFound sets a custom http.HandlerFunc for missing routes on the treeRouter.
func (mx *Mux) NotFound(h HandlerFunc) {
mx.router.notFoundHandler = &h
}
// Serve static files under a path
// FileServer conveniently sets up a http.FileServer handler to serve
// static files from a http.FileSystem.
func (mx *Mux) FileServer(path string, root http.FileSystem) {
fs := http.StripPrefix(path, http.FileServer(root))
mx.Get(path+"*", func(w http.ResponseWriter, r *http.Request) {
@ -135,6 +165,8 @@ func (mx *Mux) FileServer(path string, root http.FileSystem) {
})
}
// handle creates a chi.Handler from a chain of middlewares and an end handler,
// and then registers the route in the router.
func (mx *Mux) handle(method methodTyp, pattern string, handlers ...interface{}) {
if len(pattern) == 0 || pattern[0] != '/' {
panic(fmt.Sprintf("pattern must begin with '/' in '%s'", pattern))
@ -167,6 +199,9 @@ func (mx *Mux) handle(method methodTyp, pattern string, handlers ...interface{})
}
}
// 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 the same
// middleware(s). See _examples/ for an example usage.
func (mx *Mux) Group(fn func(r Router)) Router {
// Similarly as in handle(), we must build the mux handler once further
// middleware registration isn't allowed for this stack, like now.
@ -182,6 +217,9 @@ func (mx *Mux) Group(fn func(r Router)) Router {
return g
}
// Route creates a new Mux with a fresh middleware stack and mounts it
// along the `pattern`. This is very simiular to the Group, but attaches
// the group along a new routing path. See _examples/ for example usage.
func (mx *Mux) Route(pattern string, fn func(r Router)) Router {
subRouter := NewRouter()
mx.Mount(pattern, subRouter)
@ -191,6 +229,9 @@ func (mx *Mux) Route(pattern string, fn func(r Router)) Router {
return subRouter
}
// Mount attaches another mux 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/ for example usage.
func (mx *Mux) Mount(path string, handlers ...interface{}) {
// Build chain with any inline middlewares and endpoint handler for the subrouter
h := chain([]interface{}{}, handlers...)
@ -219,6 +260,9 @@ func (mx *Mux) Mount(path string, handlers ...interface{}) {
mx.Handle(path+"*", subHandler)
}
// 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 (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := mx.pool.Get().(*Context)
mx.ServeHTTPC(ctx, w, r)
@ -226,10 +270,14 @@ func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
mx.pool.Put(ctx)
}
// ServeHTTPC is chi's Handler method that adds a context.Context argument to the
// standard ServeHTTP handler function.
func (mx *Mux) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
mx.handler.ServeHTTPC(ctx, w, r)
}
// A treeRouter manages a radix trie prefix-router for each HTTP method and passes
// each request via its chi.Handler method.
type treeRouter struct {
// Routing tree by method type
routes map[methodTyp]*tree
@ -238,6 +286,8 @@ type treeRouter struct {
notFoundHandler *HandlerFunc
}
// newTreeRouter creates a new treeRouter object and initializes the trees for
// each http method.
func newTreeRouter() *treeRouter {
tr := &treeRouter{
routes: make(map[methodTyp]*tree, len(methodMap)),
@ -249,6 +299,7 @@ func newTreeRouter() *treeRouter {
return tr
}
// NotFoundHandlerFn returns the HandlerFunc setup on the tree.
func (tr treeRouter) NotFoundHandlerFn() HandlerFunc {
if tr.notFoundHandler != nil {
return *tr.notFoundHandler
@ -258,6 +309,7 @@ func (tr treeRouter) NotFoundHandlerFn() HandlerFunc {
})
}
// ServeHTTPC is the main routing method for each request.
func (tr treeRouter) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// Grab the root context object
rctx, _ := ctx.(*Context)

View file

@ -16,10 +16,10 @@ import (
)
func TestMux(t *testing.T) {
var count uint64 = 0
var count uint64
countermw := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count += 1
count++
next.ServeHTTP(w, r)
})
}
@ -287,9 +287,9 @@ func TestMuxNestedNotFound(t *testing.T) {
func TestMuxMiddlewareStack(t *testing.T) {
var stdmwInit, stdmwHandler uint64
stdmw := func(next http.Handler) http.Handler {
stdmwInit += 1
stdmwInit++
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
stdmwHandler += 1
stdmwHandler++
next.ServeHTTP(w, r)
})
}
@ -297,10 +297,10 @@ func TestMuxMiddlewareStack(t *testing.T) {
var ctxmwInit, ctxmwHandler uint64
ctxmw := func(next Handler) Handler {
ctxmwInit += 1
ctxmwInit++
// log.Println("INIT")
return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctxmwHandler += 1
ctxmwHandler++
ctx = context.WithValue(ctx, "count.ctxmwHandler", ctxmwHandler)
next.ServeHTTPC(ctx, w, r)
})
@ -308,9 +308,9 @@ func TestMuxMiddlewareStack(t *testing.T) {
var inCtxmwInit, inCtxmwHandler uint64
inCtxmw := func(next Handler) Handler {
inCtxmwInit += 1
inCtxmwInit++
return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
inCtxmwHandler += 1
inCtxmwHandler++
next.ServeHTTPC(ctx, w, r)
})
}
@ -339,9 +339,9 @@ func TestMuxMiddlewareStack(t *testing.T) {
})
})
var handlerCount uint64 = 0
var handlerCount uint64
r.Get("/", inCtxmw, func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
handlerCount += 1
handlerCount++
ctxmwHandlerCount := ctx.Value("count.ctxmwHandler").(uint64)
w.Write([]byte(fmt.Sprintf("inits:%d reqs:%d ctxValue:%d", ctxmwInit, handlerCount, ctxmwHandlerCount)))
})
@ -372,18 +372,18 @@ func TestMuxMiddlewareStack(t *testing.T) {
func TestMuxRootGroup(t *testing.T) {
var stdmwInit, stdmwHandler uint64
stdmw := func(next http.Handler) http.Handler {
stdmwInit += 1
stdmwInit++
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// log.Println("$$$$$ stdmw handlerfunc here!")
stdmwHandler += 1
stdmwHandler++
next.ServeHTTP(w, r)
})
}
// stdmw := func(next Handler) Handler {
// stdmwInit += 1
// stdmwInit++
// return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// log.Println("$$$$$ stdmw handlerfunc here!")
// stdmwHandler += 1
// stdmwHandler++
// next.ServeHTTPC(ctx, w, r)
// })
// }
@ -728,7 +728,7 @@ func TestMuxFileServer(t *testing.T) {
if f, ok := fixtures[name]; ok {
return f, nil
}
return nil, errors.New("file not found.")
return nil, errors.New("file not found")
}}
r := NewRouter()

View file

@ -6,6 +6,7 @@ import (
"io/ioutil"
)
// Bind is a short-hand method for decoding a JSON request body.
func Bind(r io.Reader, v interface{}) error {
defer io.Copy(ioutil.Discard, r)
return json.NewDecoder(r).Decode(v)

View file

@ -8,6 +8,7 @@ import (
"golang.org/x/net/context"
)
// A ContentType is an enumeration of HTTP content types.
type ContentType int
const (

17
tree.go
View file

@ -240,14 +240,14 @@ func (n *node) findNode(ctx *Context, path string) *node {
if fin != nil {
// found a node, return it
return fin
} else {
// let's remove the param here if it was set
if xn.typ > ntStatic {
if xn.typ == ntCatchAll {
ctx.Params.Del("*")
} else {
ctx.Params.Del(xn.prefix[1:])
}
}
// Did not found final handler, let's remove the param here if it was set
if xn.typ > ntStatic {
if xn.typ == ntCatchAll {
ctx.Params.Del("*")
} else {
ctx.Params.Del(xn.prefix[1:])
}
}
}
@ -357,7 +357,6 @@ func (t *tree) Insert(pattern string, handler Handler) {
})
return
}
return
}
func (t *tree) Find(ctx *Context, path string) Handler {