1
0
mirror of https://github.com/labstack/echo.git synced 2025-01-26 03:20:08 +02:00
Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2015-04-01 08:05:54 -07:00
parent cd9fc7fa91
commit 181d948773
5 changed files with 161 additions and 190 deletions

View File

@ -111,32 +111,32 @@ func main() {
``` ```
### Benchmark ### Benchmark
Based on [julienschmidt/go-http-routing-benchmark] (https://github.com/vishr/go-http-routing-benchmark), March 25, 2015 Based on [julienschmidt/go-http-routing-benchmark] (https://github.com/vishr/go-http-routing-benchmark), April 1, 2015
##### [GitHub API](http://developer.github.com/v3) ##### [GitHub API](http://developer.github.com/v3)
``` ```
BenchmarkAce_GithubAll 20000 70318 ns/op 13792 B/op 167 allocs/op BenchmarkAce_GithubAll 20000 69126 ns/op 13792 B/op 167 allocs/op
BenchmarkBear_GithubAll 10000 262758 ns/op 79952 B/op 943 allocs/op BenchmarkBear_GithubAll 10000 252699 ns/op 79952 B/op 943 allocs/op
BenchmarkBeego_GithubAll 3000 504264 ns/op 146272 B/op 2092 allocs/op BenchmarkBeego_GithubAll 3000 485692 ns/op 146272 B/op 2092 allocs/op
BenchmarkEcho_GithubAll 30000 45349 ns/op 0 B/op 0 allocs/op BenchmarkEcho_GithubAll 30000 43700 ns/op 0 B/op 0 allocs/op
BenchmarkBone_GithubAll 1000 2058931 ns/op 648016 B/op 8119 allocs/op BenchmarkBone_GithubAll 1000 2158467 ns/op 648016 B/op 8119 allocs/op
BenchmarkDenco_GithubAll 20000 79656 ns/op 20224 B/op 167 allocs/op BenchmarkDenco_GithubAll 20000 83022 ns/op 20224 B/op 167 allocs/op
BenchmarkGin_GithubAll 20000 71009 ns/op 13792 B/op 167 allocs/op BenchmarkGin_GithubAll 20000 72317 ns/op 13792 B/op 167 allocs/op
BenchmarkGocraftWeb_GithubAll 5000 384342 ns/op 133280 B/op 1889 allocs/op BenchmarkGocraftWeb_GithubAll 5000 381554 ns/op 133280 B/op 1889 allocs/op
BenchmarkGoji_GithubAll 3000 565323 ns/op 56113 B/op 334 allocs/op BenchmarkGoji_GithubAll 3000 605232 ns/op 56113 B/op 334 allocs/op
BenchmarkGoJsonRest_GithubAll 5000 461591 ns/op 135995 B/op 2940 allocs/op BenchmarkGoJsonRest_GithubAll 5000 467810 ns/op 135995 B/op 2940 allocs/op
BenchmarkGoRestful_GithubAll 200 8828847 ns/op 649139 B/op 7355 allocs/op BenchmarkGoRestful_GithubAll 200 9345441 ns/op 707604 B/op 7558 allocs/op
BenchmarkGorillaMux_GithubAll 200 6794821 ns/op 153137 B/op 1791 allocs/op BenchmarkGorillaMux_GithubAll 200 7043040 ns/op 153136 B/op 1791 allocs/op
BenchmarkHttpRouter_GithubAll 30000 51688 ns/op 13792 B/op 167 allocs/op BenchmarkHttpRouter_GithubAll 30000 52251 ns/op 13792 B/op 167 allocs/op
BenchmarkHttpTreeMux_GithubAll 10000 136677 ns/op 56112 B/op 334 allocs/op BenchmarkHttpTreeMux_GithubAll 10000 145114 ns/op 56112 B/op 334 allocs/op
BenchmarkKocha_GithubAll 10000 145115 ns/op 23304 B/op 843 allocs/op BenchmarkKocha_GithubAll 10000 145061 ns/op 23304 B/op 843 allocs/op
BenchmarkMacaron_GithubAll 2000 684714 ns/op 224960 B/op 2315 allocs/op BenchmarkMacaron_GithubAll 2000 697957 ns/op 224960 B/op 2315 allocs/op
BenchmarkMartini_GithubAll 100 10501805 ns/op 237953 B/op 2686 allocs/op BenchmarkMartini_GithubAll 100 11651997 ns/op 237953 B/op 2686 allocs/op
BenchmarkPat_GithubAll 500 3987941 ns/op 1504101 B/op 32222 allocs/op BenchmarkPat_GithubAll 300 3951799 ns/op 1504101 B/op 32222 allocs/op
BenchmarkRevel_GithubAll 2000 1127175 ns/op 345553 B/op 5918 allocs/op BenchmarkRevel_GithubAll 2000 1129370 ns/op 345553 B/op 5918 allocs/op
BenchmarkRivet_GithubAll 10000 239793 ns/op 84272 B/op 1079 allocs/op BenchmarkRivet_GithubAll 10000 246564 ns/op 84272 B/op 1079 allocs/op
BenchmarkTango_GithubAll 500 3452359 ns/op 1338664 B/op 27736 allocs/op BenchmarkTango_GithubAll 500 3544850 ns/op 1338664 B/op 27736 allocs/op
BenchmarkTigerTonic_GithubAll 2000 951609 ns/op 241088 B/op 6052 allocs/op BenchmarkTigerTonic_GithubAll 2000 979370 ns/op 241088 B/op 6052 allocs/op
BenchmarkTraffic_GithubAll 200 7496057 ns/op 2664761 B/op 22390 allocs/op BenchmarkTraffic_GithubAll 200 7508743 ns/op 2664762 B/op 22390 allocs/op
BenchmarkVulcan_GithubAll 5000 300807 ns/op 19894 B/op 609 allocs/op BenchmarkVulcan_GithubAll 5000 286727 ns/op 19894 B/op 609 allocs/op
BenchmarkZeus_GithubAll 2000 801269 ns/op 300688 B/op 2648 allocs/op BenchmarkZeus_GithubAll 2000 798335 ns/op 300688 B/op 2648 allocs/op
``` ```

50
echo.go
View File

@ -23,6 +23,16 @@ type (
) )
const ( const (
MethodCONNECT = "CONNECT"
MethodDELETE = "DELETE"
MethodGET = "GET"
MethodHEAD = "HEAD"
MethodOPTIONS = "OPTIONS"
MethodPATCH = "PATCH"
MethodPOST = "POST"
MethodPUT = "PUT"
MethodTRACE = "TRACE"
MIMEJSON = "application/json" MIMEJSON = "application/json"
MIMEText = "text/plain" MIMEText = "text/plain"
@ -32,6 +42,20 @@ const (
HeaderContentType = "Content-Type" HeaderContentType = "Content-Type"
) )
var (
methods = []string{
MethodCONNECT,
MethodDELETE,
MethodGET,
MethodHEAD,
MethodOPTIONS,
MethodPATCH,
MethodPOST,
MethodPUT,
MethodTRACE,
}
)
// New creates a echo instance. // New creates a echo instance.
func New() (e *Echo) { func New() (e *Echo) {
e = &Echo{ e = &Echo{
@ -99,47 +123,47 @@ func (e *Echo) Use(m ...Middleware) {
// Connect adds a CONNECT route > handler to the router. // Connect adds a CONNECT route > handler to the router.
func (e *Echo) Connect(path string, h Handler) { func (e *Echo) Connect(path string, h Handler) {
e.Router.Add("CONNECT", path, wrapH(h)) e.Router.Add(MethodCONNECT, path, wrapH(h))
} }
// Delete adds a DELETE route > handler to the router. // Delete adds a DELETE route > handler to the router.
func (e *Echo) Delete(path string, h Handler) { func (e *Echo) Delete(path string, h Handler) {
e.Router.Add("DELETE", path, wrapH(h)) e.Router.Add(MethodDELETE, path, wrapH(h))
} }
// Get adds a GET route > handler to the router. // Get adds a GET route > handler to the router.
func (e *Echo) Get(path string, h Handler) { func (e *Echo) Get(path string, h Handler) {
e.Router.Add("GET", path, wrapH(h)) e.Router.Add(MethodGET, path, wrapH(h))
} }
// Head adds a HEAD route > handler to the router. // Head adds a HEAD route > handler to the router.
func (e *Echo) Head(path string, h Handler) { func (e *Echo) Head(path string, h Handler) {
e.Router.Add("HEAD", path, wrapH(h)) e.Router.Add(MethodHEAD, path, wrapH(h))
} }
// Options adds an OPTIONS route > handler to the router. // Options adds an OPTIONS route > handler to the router.
func (e *Echo) Options(path string, h Handler) { func (e *Echo) Options(path string, h Handler) {
e.Router.Add("OPTIONS", path, wrapH(h)) e.Router.Add(MethodOPTIONS, path, wrapH(h))
} }
// Patch adds a PATCH route > handler to the router. // Patch adds a PATCH route > handler to the router.
func (e *Echo) Patch(path string, h Handler) { func (e *Echo) Patch(path string, h Handler) {
e.Router.Add("PATCH", path, wrapH(h)) e.Router.Add(MethodPATCH, path, wrapH(h))
} }
// Post adds a POST route > handler to the router. // Post adds a POST route > handler to the router.
func (e *Echo) Post(path string, h Handler) { func (e *Echo) Post(path string, h Handler) {
e.Router.Add("POST", path, wrapH(h)) e.Router.Add(MethodPOST, path, wrapH(h))
} }
// Put adds a PUT route > handler to the router. // Put adds a PUT route > handler to the router.
func (e *Echo) Put(path string, h Handler) { func (e *Echo) Put(path string, h Handler) {
e.Router.Add("PUT", path, wrapH(h)) e.Router.Add(MethodPUT, path, wrapH(h))
} }
// Trace adds a TRACE route > handler to the router. // Trace adds a TRACE route > handler to the router.
func (e *Echo) Trace(path string, h Handler) { func (e *Echo) Trace(path string, h Handler) {
e.Router.Add("TRACE", path, wrapH(h)) e.Router.Add(MethodTRACE, path, wrapH(h))
} }
// Static serves static files. // Static serves static files.
@ -163,7 +187,7 @@ func (e *Echo) Index(file string) {
} }
func (e *Echo) ServeHTTP(rw http.ResponseWriter, r *http.Request) { func (e *Echo) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
h, c, s := e.Router.Find(r.Method, r.URL.Path) h, c := e.Router.Find(r.Method, r.URL.Path)
c.reset(rw, r) c.reset(rw, r)
if h != nil { if h != nil {
// Middleware // Middleware
@ -173,11 +197,7 @@ func (e *Echo) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
// Handler // Handler
h(c) h(c)
} else { } else {
if s == NotFound { e.notFoundHandler(c)
e.notFoundHandler(c)
} else if s == NotAllowed {
e.methodNotAllowedHandler(c)
}
} }
e.pool.Put(c) e.pool.Put(c)
} }

View File

@ -153,7 +153,6 @@ func TestEchoMethod(t *testing.T) {
// if h == nil { // if h == nil {
// t.Error("should find route for GET") // t.Error("should find route for GET")
// } // }
} }
func TestEchoServeHTTP(t *testing.T) { func TestEchoServeHTTP(t *testing.T) {
@ -178,12 +177,12 @@ func TestEchoServeHTTP(t *testing.T) {
} }
// NotAllowed // NotAllowed
r, _ = http.NewRequest("POST", "/users", nil) // r, _ = http.NewRequest("POST", "/users", nil)
w = httptest.NewRecorder() // w = httptest.NewRecorder()
e.ServeHTTP(w, r) // e.ServeHTTP(w, r)
if w.Code != http.StatusMethodNotAllowed { // if w.Code != http.StatusMethodNotAllowed {
t.Errorf("status code should be 405, found %d", w.Code) // t.Errorf("status code should be 405, found %d", w.Code)
} // }
} }
func verifyUser(rd io.Reader, t *testing.T) { func verifyUser(rd io.Reader, t *testing.T) {

187
router.go
View File

@ -1,21 +1,18 @@
package echo package echo
import ( import "net/http"
"fmt"
"net/http"
)
type ( type (
router struct { router struct {
root *node trees map[string]*node
echo *Echo echo *Echo
} }
node struct { node struct {
label byte label byte
prefix string prefix string
has ntype // Type of node(s) has ntype // Type of node
handlers []HandlerFunc handler HandlerFunc
edges edges edges edges
} }
edges []*node edges []*node
ntype byte ntype byte
@ -24,7 +21,6 @@ type (
Value string Value string
} }
Params []param Params []param
Status uint16
) )
const ( const (
@ -33,44 +29,18 @@ const (
anode // Catch-all node anode // Catch-all node
) )
const ( func NewRouter(e *Echo) (r *router) {
OK Status = iota
NotFound
NotAllowed
)
// methods is a map for looking up HTTP method index.
var methods = map[string]uint8{
"CONNECT": 0,
"DELETE": 1,
"GET": 2,
"HEAD": 3,
"OPTIONS": 4,
"PATCH": 5,
"POST": 6,
"PUT": 7,
"TRACE": 8,
}
func NewRouter(b *Echo) (r *router) {
r = &router{ r = &router{
root: &node{ trees: make(map[string]*node),
prefix: "", echo: e,
handlers: make([]HandlerFunc, len(methods)),
edges: edges{},
},
echo: b,
} }
return for _, m := range methods {
} r.trees[m] = &node{
prefix: "",
func (n *node) findEdge(l byte) *node { edges: edges{},
for _, e := range n.edges {
if e.label == l {
return e
} }
} }
return nil return
} }
func (r *router) Add(method, path string, h HandlerFunc) { func (r *router) Add(method, path string, h HandlerFunc) {
@ -94,7 +64,7 @@ func (r *router) Add(method, path string, h HandlerFunc) {
} }
func (r *router) insert(method, path string, h HandlerFunc, has ntype) { func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
cn := r.root // Current node cn := r.trees[method] // Current node as root
search := path search := path
for { for {
@ -108,27 +78,27 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
cn.prefix = search cn.prefix = search
cn.has = has cn.has = has
if h != nil { if h != nil {
cn.handlers[methods[method]] = h cn.handler = h
} }
return return
} else if l < pl { } else if l < pl {
// Split the node // Split the node
n := newNode(cn.prefix[l:], cn.has, cn.handlers, cn.edges) n := newNode(cn.prefix[l:], cn.has, cn.handler, cn.edges)
cn.edges = edges{n} // Add to parent cn.edges = edges{n} // Add to parent
// Reset parent node // Reset parent node
cn.label = cn.prefix[0] cn.label = cn.prefix[0]
cn.prefix = cn.prefix[:l] cn.prefix = cn.prefix[:l]
cn.has = snode cn.has = snode
cn.handlers = make([]HandlerFunc, len(methods)) cn.handler = nil
if l == sl { if l == sl {
// At parent node // At parent node
cn.handlers[methods[method]] = h cn.handler = h
} else { } else {
// Need to fork a node // Need to fork a node
n = newNode(search[l:], has, nil, nil) n = newNode(search[l:], has, nil, nil)
n.handlers[methods[method]] = h n.handler = h
cn.edges = append(cn.edges, n) cn.edges = append(cn.edges, n)
} }
break break
@ -138,7 +108,7 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
if e == nil { if e == nil {
n := newNode(search, has, nil, nil) n := newNode(search, has, nil, nil)
if h != nil { if h != nil {
n.handlers[methods[method]] = h n.handler = h
} }
cn.edges = append(cn.edges, n) cn.edges = append(cn.edges, n)
break break
@ -148,23 +118,20 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
} else { } else {
// Node already exists // Node already exists
if h != nil { if h != nil {
cn.handlers[methods[method]] = h cn.handler = h
} }
break break
} }
} }
} }
func newNode(pfx string, has ntype, h []HandlerFunc, e edges) (n *node) { func newNode(pfx string, has ntype, h HandlerFunc, e edges) (n *node) {
n = &node{ n = &node{
label: pfx[0], label: pfx[0],
prefix: pfx, prefix: pfx,
has: has, has: has,
handlers: h, handler: h,
edges: e, edges: e,
}
if h == nil {
n.handlers = make([]HandlerFunc, len(methods))
} }
if e == nil { if e == nil {
n.edges = edges{} n.edges = edges{}
@ -172,22 +139,36 @@ func newNode(pfx string, has ntype, h []HandlerFunc, e edges) (n *node) {
return return
} }
func (r *router) Find(method, path string) (handler HandlerFunc, c *Context, s Status) { func (n *node) findEdge(l byte) *node {
for _, e := range n.edges {
if e.label == l {
return e
}
}
return nil
}
// Length of longest common prefix
func lcp(a, b string) (i int) {
max := len(a)
l := len(b)
if l < max {
max = l
}
for ; i < max && a[i] == b[i]; i++ {
}
return
}
func (r *router) Find(method, path string) (h HandlerFunc, c *Context) {
c = r.echo.pool.Get().(*Context) c = r.echo.pool.Get().(*Context)
cn := r.root // Current node cn := r.trees[method] // Current node as root
search := path search := path
n := 0 // Param count n := 0 // Param count
for { for {
if search == "" || search == cn.prefix { if search == "" || search == cn.prefix {
// Node found h = cn.handler
h := cn.handlers[methods[method]]
if h != nil {
// Handler found
handler = h
} else {
s = NotAllowed
}
return return
} }
@ -225,46 +206,17 @@ func (r *router) Find(method, path string) (handler HandlerFunc, c *Context, s S
e := cn.findEdge(search[0]) e := cn.findEdge(search[0])
if e == nil { if e == nil {
// Not found // Not found
s = NotFound
return return
} }
cn = e cn = e
continue continue
} else { } else {
// Not found // Not found
s = NotFound
return return
} }
} }
} }
// Length of longest common prefix
func lcp(a, b string) (i int) {
max := len(a)
l := len(b)
if l < max {
max = l
}
for ; i < max && a[i] == b[i]; i++ {
}
return
}
func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h, c, rep := r.Find(req.Method, req.URL.Path)
c.Response.ResponseWriter = rw
if h != nil {
h(c)
} else {
if rep == NotFound {
r.echo.notFoundHandler(c)
} else if rep == NotAllowed {
r.echo.methodNotAllowedHandler(c)
}
}
r.echo.pool.Put(c)
}
// Get returns path parameter by name. // Get returns path parameter by name.
func (ps Params) Get(n string) (v string) { func (ps Params) Get(n string) (v string) {
for _, p := range ps { for _, p := range ps {
@ -275,28 +227,13 @@ func (ps Params) Get(n string) (v string) {
return return
} }
func (r *router) printTree() { func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
r.root.printTree("", true) h, c := r.Find(req.Method, req.URL.Path)
} c.Response.ResponseWriter = rw
if h != nil {
func (n *node) printTree(pfx string, tail bool) { h(c)
p := prefix(tail, pfx, "└── ", "├── ") } else {
fmt.Printf("%s%s has=%d, len=%d\n", p, n.prefix, n.has, len(n.handlers)) r.echo.notFoundHandler(c)
nodes := n.edges
l := len(nodes)
p = prefix(tail, pfx, " ", "│ ")
for i := 0; i < l-1; i++ {
nodes[i].printTree(p, false)
}
if l > 0 {
nodes[l-1].printTree(p, true)
} }
} r.echo.pool.Put(c)
func prefix(tail bool, p, on, off string) string {
if tail {
return fmt.Sprintf("%s%s", p, on)
}
return fmt.Sprintf("%s%s", p, off)
} }

View File

@ -1,11 +1,14 @@
package echo package echo
import "testing" import (
"fmt"
"testing"
)
func TestRouterStatic(t *testing.T) { func TestRouterStatic(t *testing.T) {
r := New().Router r := New().Router
r.Add("GET", "/folders/files/bolt.gif", func(c *Context) {}) r.Add(MethodGET, "/folders/files/bolt.gif", func(c *Context) {})
h, _, _ := r.Find("GET", "/folders/files/bolt.gif") h, _ := r.Find(MethodGET, "/folders/files/bolt.gif")
if h == nil { if h == nil {
t.Fatal("handle not found") t.Fatal("handle not found")
} }
@ -13,8 +16,8 @@ func TestRouterStatic(t *testing.T) {
func TestRouterParam(t *testing.T) { func TestRouterParam(t *testing.T) {
r := New().Router r := New().Router
r.Add("GET", "/users/:id", func(c *Context) {}) r.Add(MethodGET, "/users/:id", func(c *Context) {})
h, c, _ := r.Find("GET", "/users/1") h, c := r.Find(MethodGET, "/users/1")
if h == nil { if h == nil {
t.Fatal("handle not found") t.Fatal("handle not found")
} }
@ -26,8 +29,8 @@ func TestRouterParam(t *testing.T) {
func TestRouterCatchAll(t *testing.T) { func TestRouterCatchAll(t *testing.T) {
r := New().Router r := New().Router
r.Add("GET", "/static/*", func(c *Context) {}) r.Add(MethodGET, "/static/*", func(c *Context) {})
h, _, _ := r.Find("GET", "/static/*") h, _ := r.Find(MethodGET, "/static/*")
if h == nil { if h == nil {
t.Fatal("handle not found") t.Fatal("handle not found")
} }
@ -35,8 +38,8 @@ func TestRouterCatchAll(t *testing.T) {
func TestRouterMicroParam(t *testing.T) { func TestRouterMicroParam(t *testing.T) {
r := New().Router r := New().Router
r.Add("GET", "/:a/:b/:c", func(c *Context) {}) r.Add(MethodGET, "/:a/:b/:c", func(c *Context) {})
h, c, _ := r.Find("GET", "/a/b/c") h, c := r.Find(MethodGET, "/a/b/c")
if h == nil { if h == nil {
t.Fatal("handle not found") t.Fatal("handle not found")
} }
@ -54,12 +57,24 @@ func TestRouterMicroParam(t *testing.T) {
} }
} }
func TestPrintTree(t *testing.T) { func (n *node) printTree(pfx string, tail bool) {
r := New().Router p := prefix(tail, pfx, "└── ", "├── ")
r.Add("GET", "/users", nil) fmt.Printf("%s%s has=%d\n", p, n.prefix, n.has)
r.Add("GET", "/users/:id", nil)
r.Add("GET", "/users/:id/books", nil) nodes := n.edges
r.Add("GET", "/users/:id/files", nil) l := len(nodes)
r.Add("POST", "/files", nil) p = prefix(tail, pfx, " ", "│ ")
r.printTree() for i := 0; i < l-1; i++ {
nodes[i].printTree(p, false)
}
if l > 0 {
nodes[l-1].printTree(p, true)
}
}
func prefix(tail bool, p, on, off string) string {
if tail {
return fmt.Sprintf("%s%s", p, on)
}
return fmt.Sprintf("%s%s", p, off)
} }