Skip to content

Commit

Permalink
Handling 405 & pre-flight requests
Browse files Browse the repository at this point in the history
Signed-off-by: Vishal Rana <vr@labstack.com>
  • Loading branch information
vishr committed Oct 6, 2015
1 parent 1efe837 commit 5b019c5
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 145 deletions.
4 changes: 2 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (

"net/url"

"golang.org/x/net/websocket"
"bytes"
"golang.org/x/net/websocket"
)

type (
Expand Down Expand Up @@ -115,7 +115,7 @@ func (c *Context) Render(code int, name string, data interface{}) (err error) {
if c.echo.renderer == nil {
return RendererNotRegistered
}
buf := new (bytes.Buffer)
buf := new(bytes.Buffer)
if err = c.echo.renderer.Render(buf, name, data); err != nil {
return
}
Expand Down
6 changes: 2 additions & 4 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,8 @@ var (
return NewHTTPError(http.StatusNotFound)
}

badRequestHandler = func(c *Context) error {
return NewHTTPError(http.StatusBadRequest)
methodNotAllowedHandler = func(c *Context) error {
return NewHTTPError(http.StatusMethodNotAllowed)
}
)

Expand Down Expand Up @@ -462,13 +462,11 @@ func (e *Echo) Routes() []Route {

// ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
println(r.Method)
c := e.pool.Get().(*Context)
h, echo := e.router.Find(r.Method, r.URL.Path, c)
if echo != nil {
e = echo
}
println(echo)
c.reset(r, w, e)

// Chain middleware with handler in the end
Expand Down
9 changes: 6 additions & 3 deletions echo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,12 +382,15 @@ func TestEchoNotFound(t *testing.T) {
assert.Equal(t, http.StatusNotFound, w.Code)
}

func TestEchoBadRequest(t *testing.T) {
func TestEchoMethodNotAllowed(t *testing.T) {
e := New()
r, _ := http.NewRequest("INVALID", "/files", nil)
e.Get("/", func(c *Context) error {
return c.String(http.StatusOK, "Echo!")
})
r, _ := http.NewRequest(POST, "/", nil)
w := httptest.NewRecorder()
e.ServeHTTP(w, r)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, http.StatusMethodNotAllowed, w.Code)
}

func TestEchoHTTPError(t *testing.T) {
Expand Down
228 changes: 105 additions & 123 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,33 @@ import "net/http"

type (
Router struct {
connectTree *node
deleteTree *node
getTree *node
headTree *node
optionsTree *node
patchTree *node
postTree *node
putTree *node
traceTree *node
routes []Route
echo *Echo
tree *node
routes []Route
echo *Echo
}
node struct {
typ ntype
label byte
prefix string
parent *node
children children
handler HandlerFunc
pnames []string
echo *Echo
typ ntype
label byte
prefix string
parent *node
children children
methodHandler *methodHandler
pnames []string
echo *Echo
}
ntype uint8
children []*node
methodHandler struct {
connect HandlerFunc
delete HandlerFunc
get HandlerFunc
head HandlerFunc
options HandlerFunc
patch HandlerFunc
post HandlerFunc
put HandlerFunc
trace HandlerFunc
}
ntype uint8
children []*node
)

const (
Expand All @@ -38,17 +41,11 @@ const (

func NewRouter(e *Echo) *Router {
return &Router{
connectTree: new(node),
deleteTree: new(node),
getTree: new(node),
headTree: new(node),
optionsTree: new(node),
patchTree: new(node),
postTree: new(node),
putTree: new(node),
traceTree: new(node),
routes: []Route{},
echo: e,
tree: &node{
methodHandler: new(methodHandler),
},
routes: []Route{},
echo: e,
}
}

Expand Down Expand Up @@ -90,7 +87,7 @@ func (r *Router) insert(method, path string, h HandlerFunc, t ntype, pnames []st
*e.maxParam = l
}

cn := r.findTree(method) // Current node as root
cn := r.tree // Current node as root
if cn == nil {
panic("echo => invalid method")
}
Expand All @@ -115,20 +112,20 @@ func (r *Router) insert(method, path string, h HandlerFunc, t ntype, pnames []st
cn.prefix = search
if h != nil {
cn.typ = t
cn.handler = h
cn.addHandler(method, h)
cn.pnames = pnames
cn.echo = e
}
} else if l < pl {
// Split node
n := newNode(cn.typ, cn.prefix[l:], cn, cn.children, cn.handler, cn.pnames, cn.echo)
n := newNode(cn.typ, cn.prefix[l:], cn, cn.children, cn.methodHandler, cn.pnames, cn.echo)

// Reset parent node
cn.typ = stype
cn.label = cn.prefix[0]
cn.prefix = cn.prefix[:l]
cn.children = nil
cn.handler = nil
cn.methodHandler = new(methodHandler)
cn.pnames = nil
cn.echo = nil

Expand All @@ -137,12 +134,13 @@ func (r *Router) insert(method, path string, h HandlerFunc, t ntype, pnames []st
if l == sl {
// At parent node
cn.typ = t
cn.handler = h
cn.addHandler(method, h)
cn.pnames = pnames
cn.echo = e
} else {
// Create child node
n = newNode(t, search[l:], cn, nil, h, pnames, e)
n = newNode(t, search[l:], cn, nil, new(methodHandler), pnames, e)
n.addHandler(method, h)
cn.addChild(n)
}
} else if l < sl {
Expand All @@ -154,12 +152,13 @@ func (r *Router) insert(method, path string, h HandlerFunc, t ntype, pnames []st
continue
}
// Create child node
n := newNode(t, search, cn, nil, h, pnames, e)
n := newNode(t, search, cn, nil, new(methodHandler), pnames, e)
n.addHandler(method, h)
cn.addChild(n)
} else {
// Node already exists
if h != nil {
cn.handler = h
cn.addHandler(method, h)
cn.pnames = pnames
cn.echo = e
}
Expand All @@ -168,16 +167,16 @@ func (r *Router) insert(method, path string, h HandlerFunc, t ntype, pnames []st
}
}

func newNode(t ntype, pre string, p *node, c children, h HandlerFunc, pnames []string, e *Echo) *node {
func newNode(t ntype, pre string, p *node, c children, mh *methodHandler, pnames []string, e *Echo) *node {
return &node{
typ: t,
label: pre[0],
prefix: pre,
parent: p,
children: c,
handler: h,
pnames: pnames,
echo: e,
typ: t,
label: pre[0],
prefix: pre,
parent: p,
children: c,
methodHandler: mh,
pnames: pnames,
echo: e,
}
}

Expand Down Expand Up @@ -212,76 +211,57 @@ func (n *node) findChildWithType(t ntype) *node {
return nil
}

func (r *Router) findTree(method string) (n *node) {
switch method[0] {
case 'G': // GET
m := uint32(method[2])<<8 | uint32(method[1])<<16 | uint32(method[0])<<24
if m == 0x47455400 {
n = r.getTree
}
case 'P': // POST, PUT or PATCH
switch method[1] {
case 'O': // POST
m := uint32(method[3]) | uint32(method[2])<<8 | uint32(method[1])<<16 |
uint32(method[0])<<24
if m == 0x504f5354 {
n = r.postTree
}
case 'U': // PUT
m := uint32(method[2])<<8 | uint32(method[1])<<16 | uint32(method[0])<<24
if m == 0x50555400 {
n = r.putTree
}
case 'A': // PATCH
m := uint64(method[4])<<24 | uint64(method[3])<<32 | uint64(method[2])<<40 |
uint64(method[1])<<48 | uint64(method[0])<<56
if m == 0x5041544348000000 {
n = r.patchTree
}
}
case 'D': // DELETE
m := uint64(method[5])<<16 | uint64(method[4])<<24 | uint64(method[3])<<32 |
uint64(method[2])<<40 | uint64(method[1])<<48 | uint64(method[0])<<56
if m == 0x44454c4554450000 {
n = r.deleteTree
}
case 'C': // CONNECT
m := uint64(method[6])<<8 | uint64(method[5])<<16 | uint64(method[4])<<24 |
uint64(method[3])<<32 | uint64(method[2])<<40 | uint64(method[1])<<48 |
uint64(method[0])<<56
if m == 0x434f4e4e45435400 {
n = r.connectTree
}
case 'H': // HEAD
m := uint32(method[3]) | uint32(method[2])<<8 | uint32(method[1])<<16 |
uint32(method[0])<<24
if m == 0x48454144 {
n = r.headTree
}
case 'O': // OPTIONS
m := uint64(method[6])<<8 | uint64(method[5])<<16 | uint64(method[4])<<24 |
uint64(method[3])<<32 | uint64(method[2])<<40 | uint64(method[1])<<48 |
uint64(method[0])<<56
if m == 0x4f5054494f4e5300 {
n = r.optionsTree
}
case 'T': // TRACE
m := uint64(method[4])<<24 | uint64(method[3])<<32 | uint64(method[2])<<40 |
uint64(method[1])<<48 | uint64(method[0])<<56
if m == 0x5452414345000000 {
n = r.traceTree
}
func (n *node) addHandler(method string, h HandlerFunc) {
switch method {
case GET:
n.methodHandler.get = h
case POST:
n.methodHandler.post = h
case PUT:
n.methodHandler.put = h
case DELETE:
n.methodHandler.delete = h
case PATCH:
n.methodHandler.patch = h
case OPTIONS:
n.methodHandler.delete = h
case HEAD:
n.methodHandler.head = h
case CONNECT:
n.methodHandler.connect = h
case TRACE:
n.methodHandler.trace = h
}
}

func (n *node) findHandler(method string) HandlerFunc {
switch method {
case GET:
return n.methodHandler.get
case POST:
return n.methodHandler.post
case PUT:
return n.methodHandler.put
case DELETE:
return n.methodHandler.delete
case PATCH:
return n.methodHandler.patch
case OPTIONS:
return n.methodHandler.delete
case HEAD:
return n.methodHandler.head
case CONNECT:
return n.methodHandler.connect
case TRACE:
return n.methodHandler.trace
default:
return nil
}
return
}

func (r *Router) Find(method, path string, ctx *Context) (h HandlerFunc, e *Echo) {
h = notFoundHandler
cn := r.findTree(method) // Current node as root
if cn == nil {
h = badRequestHandler
return
}
cn := r.tree // Current node as root

// Strip trailing slash
if r.echo.stripTrailingSlash {
Expand Down Expand Up @@ -339,14 +319,6 @@ func (r *Router) Find(method, path string, ctx *Context) (h HandlerFunc, e *Echo
}

if search == "" {
if cn.handler == nil {
// Look up for match-any, might have an empty value for *, e.g.
// serving a directory. Issue #207
if cn = cn.findChildWithType(mtype); cn == nil {
return
}
ctx.pvalues[len(cn.pnames)-1] = ""
}
goto Found
}

Expand Down Expand Up @@ -396,7 +368,17 @@ func (r *Router) Find(method, path string, ctx *Context) (h HandlerFunc, e *Echo

Found:
ctx.pnames = cn.pnames
h = cn.handler
h = cn.findHandler(method)
if h == nil {
h = methodNotAllowedHandler
// Look up for match-any, might have an empty value for *, e.g.
// serving a directory. Issue #207
if cn = cn.findChildWithType(mtype); cn == nil {
return
}
h = cn.findHandler(method)
ctx.pvalues[len(cn.pnames)-1] = ""
}
e = cn.echo
return
}
Expand Down

0 comments on commit 5b019c5

Please sign in to comment.