Add Wrap function to apply a list of middlewares on a handler

This commit is contained in:
Anton Zadvorny 2023-12-25 04:06:39 +03:00
parent 71df0685f4
commit 5eabae8e40
2 changed files with 55 additions and 0 deletions

19
middleware.go Normal file
View File

@ -0,0 +1,19 @@
package middleware
import (
"net/http"
)
// Wrap converts a list of middlewares to nested calls in reverse order
func Wrap(handler http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
if len(mws) == 0 {
return handler
}
res := handler
for i := len(mws) - 1; i >= 0; i-- {
res = mws[i](res)
}
return res
}

36
middleware_test.go Normal file
View File

@ -0,0 +1,36 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWrap(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/something/1/2", r.URL.Path)
})
mw1 := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path += "/1"
h.ServeHTTP(w, r)
})
}
mw2 := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path += "/2"
h.ServeHTTP(w, r)
})
}
server := httptest.NewServer(Wrap(handler, mw1, mw2))
defer server.Close()
res, err := http.Get(server.URL + "/something")
require.NoError(t, err)
assert.Equal(t, 200, res.StatusCode)
}