mirror of
https://github.com/labstack/echo.git
synced 2024-12-22 20:06:21 +02:00
echo#Use method to chain middleware #353
Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
parent
f42af6ea9f
commit
8490000762
11
echo.go
11
echo.go
@ -645,6 +645,17 @@ func (e *HTTPError) Error() string {
|
||||
return e.message
|
||||
}
|
||||
|
||||
// Use chains all middleware with handler in the end and returns head of the chain.
|
||||
// The head can be used as handler in any route.
|
||||
func Use(handler Handler, middleware ...Middleware) (h HandlerFunc) {
|
||||
h = wrapHandler(handler)
|
||||
for i := len(middleware) - 1; i >= 0; i-- {
|
||||
m := wrapMiddleware(middleware[i])
|
||||
h = m(h)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// wrapMiddleware wraps middleware.
|
||||
func wrapMiddleware(m Middleware) MiddlewareFunc {
|
||||
switch m := m.(type) {
|
||||
|
25
echo_test.go
25
echo_test.go
@ -451,6 +451,31 @@ func TestEchoHook(t *testing.T) {
|
||||
assert.Equal(t, r.URL.Path, "/test")
|
||||
}
|
||||
|
||||
func TestEchoUse(t *testing.T) {
|
||||
e := New()
|
||||
buf := new(bytes.Buffer)
|
||||
mw1 := MiddlewareFunc(func(h HandlerFunc) HandlerFunc {
|
||||
return func(c *Context) error {
|
||||
buf.WriteString("mw1")
|
||||
return h(c)
|
||||
}
|
||||
})
|
||||
mw2 := MiddlewareFunc(func(h HandlerFunc) HandlerFunc {
|
||||
return func(c *Context) error {
|
||||
buf.WriteString("mw2")
|
||||
return h(c)
|
||||
}
|
||||
})
|
||||
e.Get("/", Use(func(c *Context) error {
|
||||
return c.String(http.StatusOK, "Okay")
|
||||
}, mw1, mw2))
|
||||
|
||||
r, _ := http.NewRequest(GET, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
e.ServeHTTP(w, r)
|
||||
assert.Equal(t, "mw1mw2", buf.String())
|
||||
}
|
||||
|
||||
func testMethod(t *testing.T, method, path string, e *Echo) {
|
||||
m := fmt.Sprintf("%c%s", method[0], strings.ToLower(method[1:]))
|
||||
p := reflect.ValueOf(path)
|
||||
|
Loading…
Reference in New Issue
Block a user