Skip to content

Commit 7b843e6

Browse files
committed
Wrappers for handler and middleware
Signed-off-by: Vishal Rana <[email protected]>
1 parent 3cd1d5b commit 7b843e6

File tree

11 files changed

+147
-109
lines changed

11 files changed

+147
-109
lines changed

echo.go

Lines changed: 82 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ type (
6161

6262
MiddlewareFunc func(HandlerFunc) HandlerFunc
6363

64-
// Handler interface{}
64+
Handler interface {
65+
Handle(Context) error
66+
}
67+
6568
HandlerFunc func(Context) error
6669

6770
// HTTPErrorHandler is a centralized HTTP error handler.
@@ -181,13 +184,13 @@ var (
181184
// Error handlers
182185
//----------------
183186

184-
notFoundHandler = func(c Context) error {
187+
notFoundHandler = HandlerFunc(func(c Context) error {
185188
return NewHTTPError(http.StatusNotFound)
186-
}
189+
})
187190

188-
methodNotAllowedHandler = func(c Context) error {
191+
methodNotAllowedHandler = HandlerFunc(func(c Context) error {
189192
return NewHTTPError(http.StatusMethodNotAllowed)
190-
}
193+
})
191194
)
192195

193196
// New creates an instance of Echo.
@@ -204,22 +207,7 @@ func New() (e *Echo) {
204207
//----------
205208

206209
e.HTTP2(true)
207-
e.defaultHTTPErrorHandler = func(err error, c Context) {
208-
code := http.StatusInternalServerError
209-
msg := http.StatusText(code)
210-
if he, ok := err.(*HTTPError); ok {
211-
code = he.code
212-
msg = he.message
213-
}
214-
if e.debug {
215-
msg = err.Error()
216-
}
217-
if !c.Response().Committed() {
218-
c.String(code, msg)
219-
}
220-
e.logger.Error(err)
221-
}
222-
e.SetHTTPErrorHandler(e.defaultHTTPErrorHandler)
210+
e.SetHTTPErrorHandler(e.DefaultHTTPErrorHandler)
223211
e.SetBinder(&binder{})
224212

225213
// Logger
@@ -232,6 +220,10 @@ func (f MiddlewareFunc) Process(h HandlerFunc) HandlerFunc {
232220
return f(h)
233221
}
234222

223+
func (f HandlerFunc) Handle(c Context) error {
224+
return f(c)
225+
}
226+
235227
// Router returns router.
236228
func (e *Echo) Router() *Router {
237229
return e.router
@@ -254,7 +246,19 @@ func (e *Echo) HTTP2(on bool) {
254246

255247
// DefaultHTTPErrorHandler invokes the default HTTP error handler.
256248
func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
257-
e.defaultHTTPErrorHandler(err, c)
249+
code := http.StatusInternalServerError
250+
msg := http.StatusText(code)
251+
if he, ok := err.(*HTTPError); ok {
252+
code = he.code
253+
msg = he.message
254+
}
255+
if e.debug {
256+
msg = err.Error()
257+
}
258+
if !c.Response().Committed() {
259+
c.String(code, msg)
260+
}
261+
e.logger.Error(err)
258262
}
259263

260264
// SetHTTPErrorHandler registers a custom Echo.HTTPErrorHandler.
@@ -295,75 +299,75 @@ func (e *Echo) Hook(h engine.HandlerFunc) {
295299
}
296300

297301
// Use adds handler to the middleware chain.
298-
func (e *Echo) Use(m ...MiddlewareFunc) {
299-
for _, h := range m {
300-
e.middleware = append(e.middleware, h)
302+
func (e *Echo) Use(middleware ...interface{}) {
303+
for _, m := range middleware {
304+
e.middleware = append(e.middleware, wrapMiddleware(m))
301305
}
302306
}
303307

304308
// Connect adds a CONNECT route > handler to the router.
305-
func (e *Echo) Connect(path string, h HandlerFunc) {
306-
e.add(CONNECT, path, h)
309+
func (e *Echo) Connect(path string, handler interface{}) {
310+
e.add(CONNECT, path, handler)
307311
}
308312

309313
// Delete adds a DELETE route > handler to the router.
310-
func (e *Echo) Delete(path string, h HandlerFunc) {
311-
e.add(DELETE, path, h)
314+
func (e *Echo) Delete(path string, handler interface{}) {
315+
e.add(DELETE, path, handler)
312316
}
313317

314318
// Get adds a GET route > handler to the router.
315-
func (e *Echo) Get(path string, h HandlerFunc) {
316-
e.add(GET, path, h)
319+
func (e *Echo) Get(path string, handler interface{}) {
320+
e.add(GET, path, handler)
317321
}
318322

319323
// Head adds a HEAD route > handler to the router.
320-
func (e *Echo) Head(path string, h HandlerFunc) {
321-
e.add(HEAD, path, h)
324+
func (e *Echo) Head(path string, handler interface{}) {
325+
e.add(HEAD, path, handler)
322326
}
323327

324328
// Options adds an OPTIONS route > handler to the router.
325-
func (e *Echo) Options(path string, h HandlerFunc) {
326-
e.add(OPTIONS, path, h)
329+
func (e *Echo) Options(path string, handler interface{}) {
330+
e.add(OPTIONS, path, handler)
327331
}
328332

329333
// Patch adds a PATCH route > handler to the router.
330-
func (e *Echo) Patch(path string, h HandlerFunc) {
331-
e.add(PATCH, path, h)
334+
func (e *Echo) Patch(path string, handler interface{}) {
335+
e.add(PATCH, path, handler)
332336
}
333337

334338
// Post adds a POST route > handler to the router.
335-
func (e *Echo) Post(path string, h HandlerFunc) {
336-
e.add(POST, path, h)
339+
func (e *Echo) Post(path string, handler interface{}) {
340+
e.add(POST, path, handler)
337341
}
338342

339343
// Put adds a PUT route > handler to the router.
340-
func (e *Echo) Put(path string, h HandlerFunc) {
341-
e.add(PUT, path, h)
344+
func (e *Echo) Put(path string, handler interface{}) {
345+
e.add(PUT, path, handler)
342346
}
343347

344348
// Trace adds a TRACE route > handler to the router.
345-
func (e *Echo) Trace(path string, h HandlerFunc) {
346-
e.add(TRACE, path, h)
349+
func (e *Echo) Trace(path string, handler interface{}) {
350+
e.add(TRACE, path, handler)
347351
}
348352

349353
// Any adds a route > handler to the router for all HTTP methods.
350-
func (e *Echo) Any(path string, h HandlerFunc) {
354+
func (e *Echo) Any(path string, handler interface{}) {
351355
for _, m := range methods {
352-
e.add(m, path, h)
356+
e.add(m, path, handler)
353357
}
354358
}
355359

356360
// Match adds a route > handler to the router for multiple HTTP methods provided.
357-
func (e *Echo) Match(methods []string, path string, h HandlerFunc) {
361+
func (e *Echo) Match(methods []string, path string, handler interface{}) {
358362
for _, m := range methods {
359-
e.add(m, path, h)
363+
e.add(m, path, handler)
360364
}
361365
}
362366

363367
// NOTE: v2
364-
func (e *Echo) add(method, path string, h HandlerFunc) {
368+
func (e *Echo) add(method, path string, h interface{}) {
365369
path = e.prefix + path
366-
e.router.Add(method, path, h, e)
370+
e.router.Add(method, path, wrapHandler(h), e)
367371
r := Route{
368372
Method: method,
369373
Path: path,
@@ -511,8 +515,7 @@ func (e *Echo) Routes() []Route {
511515
return e.router.routes
512516
}
513517

514-
// ServeHTTP serves HTTP requests.
515-
func (e *Echo) ServeHTTP(req engine.Request, res engine.Response) {
518+
func (e *Echo) handle(req engine.Request, res engine.Response) {
516519
if e.hook != nil {
517520
e.hook(req, res)
518521
}
@@ -566,33 +569,11 @@ func (e *Echo) RunTLS(addr, certfile, keyfile string) {
566569

567570
// RunConfig runs a server with engine configuration.
568571
func (e *Echo) RunConfig(config *engine.Config) {
569-
handler := func(req engine.Request, res engine.Response) {
570-
if e.hook != nil {
571-
e.hook(req, res)
572-
}
573-
574-
c := e.pool.Get().(*context)
575-
h, e := e.router.Find(req.Method(), req.URL().Path(), c)
576-
c.reset(req, res, e)
577-
578-
// Chain middleware with handler in the end
579-
for i := len(e.middleware) - 1; i >= 0; i-- {
580-
h = e.middleware[i](h)
581-
}
582-
583-
// Execute chain
584-
if err := h(c); err != nil {
585-
e.httpErrorHandler(err, c)
586-
}
587-
588-
e.pool.Put(c)
589-
}
590-
591572
switch e.engineType {
592573
case engine.FastHTTP:
593-
e.engine = fasthttp.NewServer(config, handler, e.logger)
574+
e.engine = fasthttp.NewServer(config, e.handle, e.logger)
594575
default:
595-
e.engine = standard.NewServer(config, handler, e.logger)
576+
e.engine = standard.NewServer(config, e.handle, e.logger)
596577
}
597578
e.engine.Start()
598579
}
@@ -635,3 +616,29 @@ func (binder) Bind(r engine.Request, i interface{}) (err error) {
635616
}
636617
return
637618
}
619+
620+
func wrapMiddleware(m interface{}) MiddlewareFunc {
621+
switch m := m.(type) {
622+
case Middleware:
623+
return m.Process
624+
case MiddlewareFunc:
625+
return m
626+
case func(HandlerFunc) HandlerFunc:
627+
return m
628+
default:
629+
panic("invalid middleware")
630+
}
631+
}
632+
633+
func wrapHandler(h interface{}) HandlerFunc {
634+
switch h := h.(type) {
635+
case Handler:
636+
return h.Handle
637+
case HandlerFunc:
638+
return h
639+
case func(Context) error:
640+
return h
641+
default:
642+
panic("invalid handler")
643+
}
644+
}

echo_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ func TestEchoNotFound(t *testing.T) {
308308
e := New()
309309
req := test.NewRequest(GET, "/files", nil)
310310
rec := test.NewResponseRecorder()
311-
e.ServeHTTP(req, rec)
311+
e.handle(req, rec)
312312
assert.Equal(t, http.StatusNotFound, rec.Status())
313313
}
314314

@@ -319,7 +319,7 @@ func TestEchoMethodNotAllowed(t *testing.T) {
319319
})
320320
req := test.NewRequest(POST, "/", nil)
321321
rec := test.NewResponseRecorder()
322-
e.ServeHTTP(req, rec)
322+
e.handle(req, rec)
323323
assert.Equal(t, http.StatusMethodNotAllowed, rec.Status())
324324
}
325325

@@ -350,7 +350,7 @@ func TestEchoHook(t *testing.T) {
350350
})
351351
req := test.NewRequest(GET, "/test/", nil)
352352
rec := test.NewResponseRecorder()
353-
e.ServeHTTP(req, rec)
353+
e.handle(req, rec)
354354
assert.Equal(t, req.URL().Path(), "/test")
355355
}
356356

@@ -371,6 +371,6 @@ func testMethod(t *testing.T, method, path string, e *Echo) {
371371
func request(method, path string, e *Echo) (int, string) {
372372
req := test.NewRequest(method, path, nil)
373373
rec := test.NewResponseRecorder()
374-
e.ServeHTTP(req, rec)
374+
e.handle(req, rec)
375375
return rec.Status(), rec.Body.String()
376376
}

engine/fasthttp/header.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import "github.com/valyala/fasthttp"
44

55
type (
66
RequestHeader struct {
7-
fasthttp.RequestHeader
7+
header fasthttp.RequestHeader
88
}
99

1010
ResponseHeader struct {
11-
fasthttp.ResponseHeader
11+
header fasthttp.ResponseHeader
1212
}
1313
)
1414

@@ -17,23 +17,24 @@ func (h *RequestHeader) Add(key, val string) {
1717
}
1818

1919
func (h *RequestHeader) Del(key string) {
20-
h.RequestHeader.Del(key)
20+
h.header.Del(key)
2121
}
2222

2323
func (h *RequestHeader) Get(key string) string {
24-
return string(h.RequestHeader.Peek(key))
24+
// return h.header.Peek(key)
25+
return ""
2526
}
2627

2728
func (h *RequestHeader) Set(key, val string) {
28-
h.RequestHeader.Set(key, val)
29+
h.header.Set(key, val)
2930
}
3031

3132
func (h *ResponseHeader) Add(key, val string) {
32-
// h.ResponseHeader.Add(key, val)
33+
// h.header.Add(key, val)
3334
}
3435

3536
func (h *ResponseHeader) Del(key string) {
36-
h.ResponseHeader.Del(key)
37+
h.header.Del(key)
3738
}
3839

3940
func (h *ResponseHeader) Get(key string) string {
@@ -42,5 +43,5 @@ func (h *ResponseHeader) Get(key string) string {
4243
}
4344

4445
func (h *ResponseHeader) Set(key, val string) {
45-
h.ResponseHeader.Set(key, val)
46+
h.header.Set(key, val)
4647
}

engine/fasthttp/request.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,26 @@ import (
99

1010
type (
1111
Request struct {
12-
request *fasthttp.RequestCtx
12+
context *fasthttp.RequestCtx
1313
url engine.URL
1414
header engine.Header
1515
}
1616
)
1717

18+
func NewRequest(c *fasthttp.RequestCtx) *Request {
19+
return &Request{
20+
context: c,
21+
url: &URL{url: c.URI()},
22+
header: &RequestHeader{c.Request.Header},
23+
}
24+
}
25+
1826
func (r *Request) Object() interface{} {
19-
return r.request
27+
return r.context
2028
}
2129

2230
func (r *Request) URI() string {
23-
return string(r.request.RequestURI())
31+
return string(r.context.RequestURI())
2432
}
2533

2634
func (r *Request) URL() engine.URL {
@@ -32,11 +40,11 @@ func (r *Request) Header() engine.Header {
3240
}
3341

3442
func (r *Request) RemoteAddress() string {
35-
return r.request.RemoteAddr().String()
43+
return r.context.RemoteAddr().String()
3644
}
3745

3846
func (r *Request) Method() string {
39-
return string(r.request.Method())
47+
return string(r.context.Method())
4048
}
4149

4250
func (r *Request) Body() io.ReadCloser {

0 commit comments

Comments
 (0)