1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Changes for sub router #10

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2015-04-02 05:02:52 -07:00
parent 0337e9d13f
commit d8aae6ea43
9 changed files with 138 additions and 74 deletions

View File

@ -16,6 +16,7 @@ Echo is a fast HTTP router (zero memory allocation) + micro web framework in Go.
- `http.Handler`
- `http.HandlerFunc`
- `func(http.ResponseWriter, *http.Request)`
- Sub router
- Handy encoding/decoding functions.
- Serve static files, including index.
@ -104,10 +105,18 @@ func main() {
e.Get("/users", getUsers)
e.Get("/users/:id", getUser)
// Sub router
a := e.Sub("/admin")
a.Use(func(c *echo.Context) {
// Security check
})
a.Get("", func(c *echo.Context) {
c.String(200, "Welcome to the secured area!")
})
// Start server
e.Run(":8080")
}
```
### Benchmark

View File

@ -82,7 +82,8 @@ func (c *Context) Redirect(n int, url string) {
http.Redirect(c.Response, c.Request, url, n)
}
func (c *Context) reset(rw http.ResponseWriter, r *http.Request) {
func (c *Context) reset(rw http.ResponseWriter, r *http.Request, e *Echo) {
c.Response.reset(rw)
c.Request = r
c.echo = e
}

View File

@ -39,7 +39,7 @@ func TestContext(t *testing.T) {
b, _ := json.Marshal(u)
w := httptest.NewRecorder()
r, _ := http.NewRequest("PUT", "/users/1", bytes.NewReader(b))
r, _ := http.NewRequest(MethodPUT, "/users/1", bytes.NewReader(b))
r.Header.Add(HeaderContentType, MIMEJSON)
e.ServeHTTP(w, r)
if w.Code != http.StatusCreated {

76
echo.go
View File

@ -8,7 +8,9 @@ import (
type (
Echo struct {
id uint8
Router *router
prefix string
middleware []MiddlewareFunc
maxParam byte
notFoundHandler HandlerFunc
@ -16,10 +18,10 @@ type (
internalServerErrorHandler HandlerFunc
pool sync.Pool
}
Handler interface{}
HandlerFunc func(*Context)
Middleware interface{}
MiddlewareFunc func(HandlerFunc) HandlerFunc
Handler interface{}
HandlerFunc func(*Context)
)
const (
@ -43,7 +45,9 @@ const (
)
var (
methods = []string{
subs = [128]*Echo{} // Sub routers
methods = [...]string{
MethodCONNECT,
MethodDELETE,
MethodGET,
@ -76,22 +80,25 @@ func New() (e *Echo) {
Response: &response{},
params: make(Params, e.maxParam),
store: make(store),
echo: e,
echo: e, // TODO: Do we need it?
}
}
return
}
// NOP
func (h HandlerFunc) ServeHTTP(r http.ResponseWriter, w *http.Request) {
func (h HandlerFunc) ServeHTTP(http.ResponseWriter, *http.Request) {
}
// func (b *Echo) Sub(prefix string, m ...MiddlewareFunc) *Echo {
// return &Echo{
// prefix: b.prefix + prefix,
// middleware: append(b.handlers, handlers...),
// }
// }
// Sub creates a new sub router, inherits all properties from the parent router
// including middleware.
func (e *Echo) Sub(pfx string) *Echo {
s := *e
s.id++
s.prefix = pfx
subs[s.id] = &s
return &s
}
// MaxParam sets the maximum allowed path parameters. Default is 5, good enough
// for many users.
@ -123,47 +130,51 @@ func (e *Echo) Use(m ...Middleware) {
// Connect adds a CONNECT route > handler to the router.
func (e *Echo) Connect(path string, h Handler) {
e.Router.Add(MethodCONNECT, path, wrapH(h))
e.add(MethodCONNECT, path, h)
}
// Delete adds a DELETE route > handler to the router.
func (e *Echo) Delete(path string, h Handler) {
e.Router.Add(MethodDELETE, path, wrapH(h))
e.add(MethodDELETE, path, h)
}
// Get adds a GET route > handler to the router.
func (e *Echo) Get(path string, h Handler) {
e.Router.Add(MethodGET, path, wrapH(h))
e.add(MethodGET, path, h)
}
// Head adds a HEAD route > handler to the router.
func (e *Echo) Head(path string, h Handler) {
e.Router.Add(MethodHEAD, path, wrapH(h))
e.add(MethodHEAD, path, h)
}
// Options adds an OPTIONS route > handler to the router.
func (e *Echo) Options(path string, h Handler) {
e.Router.Add(MethodOPTIONS, path, wrapH(h))
e.add(MethodOPTIONS, path, h)
}
// Patch adds a PATCH route > handler to the router.
func (e *Echo) Patch(path string, h Handler) {
e.Router.Add(MethodPATCH, path, wrapH(h))
e.add(MethodPATCH, path, h)
}
// Post adds a POST route > handler to the router.
func (e *Echo) Post(path string, h Handler) {
e.Router.Add(MethodPOST, path, wrapH(h))
e.add(MethodPOST, path, h)
}
// Put adds a PUT route > handler to the router.
func (e *Echo) Put(path string, h Handler) {
e.Router.Add(MethodPUT, path, wrapH(h))
e.add(MethodPUT, path, h)
}
// Trace adds a TRACE route > handler to the router.
func (e *Echo) Trace(path string, h Handler) {
e.Router.Add(MethodTRACE, path, wrapH(h))
e.add(MethodTRACE, path, h)
}
func (e *Echo) add(method, path string, h Handler) {
e.Router.Add(method, e.prefix+path, wrapH(h), e.id)
}
// Static serves static files.
@ -187,18 +198,21 @@ func (e *Echo) Index(file string) {
}
func (e *Echo) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
h, c := e.Router.Find(r.Method, r.URL.Path)
c.reset(rw, r)
if h != nil {
// Middleware
for i := len(e.middleware) - 1; i >= 0; i-- {
h = e.middleware[i](h)
}
// Handler
h(c)
} else {
e.notFoundHandler(c)
h, c, eid := e.Router.Find(r.Method, r.URL.Path)
if h == nil {
h = e.notFoundHandler
}
if eid != 0 {
// It's a sub router
e = subs[eid]
}
c.reset(rw, r, e)
// Middleware
for i := len(e.middleware) - 1; i >= 0; i-- {
h = e.middleware[i](h)
}
// Handler
h(c)
e.pool.Put(c)
}

View File

@ -34,7 +34,7 @@ func TestEchoIndex(t *testing.T) {
e := New()
e.Index("example/public/index.html")
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/", nil)
r, _ := http.NewRequest(MethodGET, "/", nil)
e.ServeHTTP(w, r)
if w.Code != 200 {
t.Errorf("status code should be 200, found %d", w.Code)
@ -45,7 +45,7 @@ func TestEchoStatic(t *testing.T) {
e := New()
e.Static("/js", "example/public/js")
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/js/main.js", nil)
r, _ := http.NewRequest(MethodGET, "/js/main.js", nil)
e.ServeHTTP(w, r)
if w.Code != 200 {
t.Errorf("status code should be 200, found %d", w.Code)
@ -98,7 +98,7 @@ func TestEchoMiddleware(t *testing.T) {
})
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/hello", nil)
r, _ := http.NewRequest(MethodGET, "/hello", nil)
e.ServeHTTP(w, r)
if b.String() != "abcdef" {
t.Errorf("buffer should be abcdef, found %s", b.String())
@ -116,7 +116,7 @@ func TestEchoHandler(t *testing.T) {
c.String(http.StatusOK, "1")
})
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/1", nil)
r, _ := http.NewRequest(MethodGET, "/1", nil)
e.ServeHTTP(w, r)
if w.Body.String() != "1" {
t.Error("body should be 1")
@ -127,7 +127,7 @@ func TestEchoHandler(t *testing.T) {
w.Write([]byte("2"))
}))
w = httptest.NewRecorder()
r, _ = http.NewRequest("GET", "/2", nil)
r, _ = http.NewRequest(MethodGET, "/2", nil)
e.ServeHTTP(w, r)
if w.Body.String() != "2" {
t.Error("body should be 2")
@ -138,13 +138,44 @@ func TestEchoHandler(t *testing.T) {
w.Write([]byte("3"))
})
w = httptest.NewRecorder()
r, _ = http.NewRequest("GET", "/3", nil)
r, _ = http.NewRequest(MethodGET, "/3", nil)
e.ServeHTTP(w, r)
if w.Body.String() != "3" {
t.Error("body should be 3")
}
}
func TestEchoSub(t *testing.T) {
b := new(bytes.Buffer)
e := New()
e.Use(func(*Context) {
b.WriteString("1")
})
e.Get("/users", func(*Context) {})
s := e.Sub("/sub")
s.Use(func(*Context) {
b.WriteString("2")
})
s.Get("", func(*Context) {})
w := httptest.NewRecorder()
r, _ := http.NewRequest(MethodGET, "/users", nil)
e.ServeHTTP(w, r)
if b.String() != "1" {
t.Errorf("should only execute middleware 1, executed %s", b.String())
}
b.Reset()
w = httptest.NewRecorder()
r, _ = http.NewRequest(MethodGET, "/sub", nil)
e.ServeHTTP(w, r)
if b.String() != "12" {
t.Errorf("should execute middleware 1 & 2, executed %s", b.String())
}
}
func TestEchoMethod(t *testing.T) {
// e := New()
// // GET
@ -159,17 +190,17 @@ func TestEchoServeHTTP(t *testing.T) {
e := New()
// OK
e.Get("/users", func(c *Context) {
e.Get("/users", func(*Context) {
})
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/users", nil)
r, _ := http.NewRequest(MethodGET, "/users", nil)
e.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("status code should be 200, found %d", w.Code)
}
// NotFound
r, _ = http.NewRequest("GET", "/user", nil)
r, _ = http.NewRequest(MethodGET, "/user", nil)
w = httptest.NewRecorder()
e.ServeHTTP(w, r)
if w.Code != http.StatusNotFound {

View File

@ -76,6 +76,15 @@ func main() {
e.Get("/users", getUsers)
e.Get("/users/:id", getUser)
// Sub router
a := e.Sub("/admin")
a.Use(func(c *echo.Context) {
// Security check
})
a.Get("", func(c *echo.Context) {
c.String(200, "Welcome to the secured area!")
})
// Start server
e.Run(":8080")
}

View File

@ -52,7 +52,7 @@ func (r *response) Flusher() {
func (r *response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := r.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("bolt: hijacker interface not supported")
return nil, nil, errors.New("echo: hijacker interface not supported")
}
return h.Hijack()
}

View File

@ -10,8 +10,9 @@ type (
node struct {
label byte
prefix string
has ntype // Type of node
has ntype // Type of node it contains
handler HandlerFunc
eid uint8 // Echo id
edges edges
}
edges []*node
@ -43,27 +44,27 @@ func NewRouter(e *Echo) (r *router) {
return
}
func (r *router) Add(method, path string, h HandlerFunc) {
func (r *router) Add(method, path string, h HandlerFunc, eid uint8) {
i := 0
l := len(path)
for ; i < l; i++ {
if path[i] == ':' {
r.insert(method, path[:i], nil, pnode)
r.insert(method, path[:i], nil, eid, pnode)
for ; i < l && path[i] != '/'; i++ {
}
if i == l {
r.insert(method, path[:i], h, snode)
r.insert(method, path[:i], h, eid, snode)
return
}
r.insert(method, path[:i], nil, snode)
r.insert(method, path[:i], nil, eid, snode)
} else if path[i] == '*' {
r.insert(method, path[:i], h, anode)
r.insert(method, path[:i], h, eid, anode)
}
}
r.insert(method, path, h, snode)
r.insert(method, path, h, eid, snode)
}
func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
func (r *router) insert(method, path string, h HandlerFunc, eid uint8, has ntype) {
cn := r.trees[method] // Current node as root
search := path
@ -79,11 +80,12 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
cn.has = has
if h != nil {
cn.handler = h
cn.eid = eid
}
return
} else if l < pl {
// Split the node
n := newNode(cn.prefix[l:], cn.has, cn.handler, cn.edges)
n := newNode(cn.prefix[l:], cn.has, cn.handler, cn.eid, cn.edges)
cn.edges = edges{n} // Add to parent
// Reset parent node
@ -91,14 +93,15 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
cn.prefix = cn.prefix[:l]
cn.has = snode
cn.handler = nil
cn.eid = 0
if l == sl {
// At parent node
cn.handler = h
cn.eid = eid
} else {
// Need to fork a node
n = newNode(search[l:], has, nil, nil)
n.handler = h
n = newNode(search[l:], has, h, eid, edges{})
cn.edges = append(cn.edges, n)
}
break
@ -106,10 +109,7 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
search = search[l:]
e := cn.findEdge(search[0])
if e == nil {
n := newNode(search, has, nil, nil)
if h != nil {
n.handler = h
}
n := newNode(search, has, h, eid, edges{})
cn.edges = append(cn.edges, n)
break
} else {
@ -119,23 +119,22 @@ func (r *router) insert(method, path string, h HandlerFunc, has ntype) {
// Node already exists
if h != nil {
cn.handler = h
cn.eid = eid
}
break
}
}
}
func newNode(pfx string, has ntype, h HandlerFunc, e edges) (n *node) {
func newNode(pfx string, has ntype, h HandlerFunc, eid uint8, e edges) (n *node) {
n = &node{
label: pfx[0],
prefix: pfx,
has: has,
handler: h,
eid: eid,
edges: e,
}
if e == nil {
n.edges = edges{}
}
return
}
@ -160,7 +159,7 @@ func lcp(a, b string) (i int) {
return
}
func (r *router) Find(method, path string) (h HandlerFunc, c *Context) {
func (r *router) Find(method, path string) (h HandlerFunc, c *Context, eid uint8) {
c = r.echo.pool.Get().(*Context)
cn := r.trees[method] // Current node as root
search := path
@ -169,6 +168,7 @@ func (r *router) Find(method, path string) (h HandlerFunc, c *Context) {
for {
if search == "" || search == cn.prefix {
h = cn.handler
eid = cn.eid
return
}
@ -228,7 +228,7 @@ func (ps Params) Get(n string) (v string) {
}
func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h, c := r.Find(req.Method, req.URL.Path)
h, c, _ := r.Find(req.Method, req.URL.Path)
c.Response.ResponseWriter = rw
if h != nil {
h(c)

View File

@ -7,8 +7,8 @@ import (
func TestRouterStatic(t *testing.T) {
r := New().Router
r.Add(MethodGET, "/folders/files/bolt.gif", func(c *Context) {})
h, _ := r.Find(MethodGET, "/folders/files/bolt.gif")
r.Add(MethodGET, "/folders/files/echo.gif", func(c *Context) {}, 0)
h, _, _ := r.Find(MethodGET, "/folders/files/echo.gif")
if h == nil {
t.Fatal("handle not found")
}
@ -16,8 +16,8 @@ func TestRouterStatic(t *testing.T) {
func TestRouterParam(t *testing.T) {
r := New().Router
r.Add(MethodGET, "/users/:id", func(c *Context) {})
h, c := r.Find(MethodGET, "/users/1")
r.Add(MethodGET, "/users/:id", func(c *Context) {}, 0)
h, c, _ := r.Find(MethodGET, "/users/1")
if h == nil {
t.Fatal("handle not found")
}
@ -29,8 +29,8 @@ func TestRouterParam(t *testing.T) {
func TestRouterCatchAll(t *testing.T) {
r := New().Router
r.Add(MethodGET, "/static/*", func(c *Context) {})
h, _ := r.Find(MethodGET, "/static/*")
r.Add(MethodGET, "/static/*", func(c *Context) {}, 0)
h, _, _ := r.Find(MethodGET, "/static/*")
if h == nil {
t.Fatal("handle not found")
}
@ -38,8 +38,8 @@ func TestRouterCatchAll(t *testing.T) {
func TestRouterMicroParam(t *testing.T) {
r := New().Router
r.Add(MethodGET, "/:a/:b/:c", func(c *Context) {})
h, c := r.Find(MethodGET, "/a/b/c")
r.Add(MethodGET, "/:a/:b/:c", func(c *Context) {}, 0)
h, c, _ := r.Find(MethodGET, "/a/b/c")
if h == nil {
t.Fatal("handle not found")
}
@ -59,7 +59,7 @@ func TestRouterMicroParam(t *testing.T) {
func (n *node) printTree(pfx string, tail bool) {
p := prefix(tail, pfx, "└── ", "├── ")
fmt.Printf("%s%s has=%d\n", p, n.prefix, n.has)
fmt.Printf("%s%s has=%d, h=%v, eid=%d\n", p, n.prefix, n.has, n.handler, n.eid)
nodes := n.edges
l := len(nodes)