Skip to content
This repository has been archived by the owner on Feb 24, 2024. It is now read-only.

Commit

Permalink
Task middleware remove (#1826)
Browse files Browse the repository at this point in the history
* adding middleware remove
  • Loading branch information
paganotoni authored Nov 6, 2019
1 parent 90d4c70 commit 9b3f3be
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
23 changes: 23 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,29 @@ func (ms *MiddlewareStack) Use(mw ...MiddlewareFunc) {
ms.stack = append(ms.stack, mw...)
}

// Remove the specified Middleware(s) for the App/group. This is useful when
// the middleware will be skipped by the entire group.
/*
a.Middleware.Remove(Authorization)
*/
func (ms *MiddlewareStack) Remove(mws ...MiddlewareFunc) {
result := []MiddlewareFunc{}

base:
for _, existing := range ms.stack {
for _, banned := range mws {
if funcKey(existing) == funcKey(banned) {
continue base
}
}

result = append(result, existing)
}

ms.stack = result

}

// Skip a specified piece of middleware the specified Handlers.
// This is useful for things like wrapping your application in an
// authorization middleware, but skipping it for things the home
Expand Down
43 changes: 43 additions & 0 deletions middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,46 @@ func Test_Middleware_Clear(t *testing.T) {
r.Len(mws.stack, 0)
r.Len(mws.skips, 0)
}

func Test_Middleware_Remove(t *testing.T) {
r := require.New(t)
log := []string{}

mw1 := func(h Handler) Handler {
log = append(log, "mw1")
return h
}

mw2 := func(h Handler) Handler {
log = append(log, "mw2")
return h
}

a := New(Options{})
a.Use(mw2)
a.Use(mw1)

var cr Resource = &carsResource{}
g := a.Resource("/autos", cr)
g.Middleware.Remove(mw2)

a.Resource("/all_log_autos", cr)
w := httptest.New(a)

ng := a.Resource("/no_log_autos", cr)
ng.Middleware.Remove(mw1, mw2)

_ = w.HTML("/autos/1").Get()
r.Len(log, 1)
r.Equal("mw1", log[0])

log = []string{}
_ = w.HTML("/all_log_autos/1").Get()
r.Len(log, 2)
r.Contains(log, "mw2")
r.Contains(log, "mw1")

log = []string{}
_ = w.HTML("/no_log_autos/1").Get()
r.Len(log, 0)
}

0 comments on commit 9b3f3be

Please sign in to comment.