Skip to content

Commit

Permalink
added generic middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
johnabass committed Jun 24, 2023
1 parent ea6efb4 commit 6af4643
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
16 changes: 16 additions & 0 deletions arrangehttp/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package arrangehttp

// Middleware is the underlying type for decorators.
type Middleware[T any] interface {
~func(T) T
}

// ApplyMiddleware handles decorating a target type T. Middleware
// executes in the order declared to this function.
func ApplyMiddleware[T any, M Middleware[T]](t T, m ...M) T {
for i := len(m) - 1; i >= 0; i-- {
t = m[i](t)
}

return t
}
44 changes: 44 additions & 0 deletions arrangehttp/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package arrangehttp

import (
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/suite"
)

type MiddlewareSuite struct {
suite.Suite
}

func (suite *MiddlewareSuite) testApplyMiddleware(count int) {
current := count - 1 // middleware themselves run in reverse order
middleware := make([]func(http.Handler) http.Handler, 0, count)
for i := 0; i < count; i++ {
i := i
middleware = append(middleware, func(actual http.Handler) http.Handler {
suite.Same(http.DefaultServeMux, actual)
suite.Equal(i, current)
current--
return actual
})
}

suite.Equal(
http.DefaultServeMux,
ApplyMiddleware[http.Handler](http.DefaultServeMux, middleware...),
)
}

func (suite *MiddlewareSuite) TestApplyMiddleware() {
for _, count := range []int{0, 1, 2, 5} {
suite.Run(fmt.Sprintf("count=%d", count), func() {
suite.testApplyMiddleware(count)
})
}
}

func TestMiddleware(t *testing.T) {
suite.Run(t, new(MiddlewareSuite))
}

0 comments on commit 6af4643

Please sign in to comment.