Add Wrap function to apply a list of middlewares on a handler
This commit is contained in:
parent
71df0685f4
commit
5eabae8e40
19
middleware.go
Normal file
19
middleware.go
Normal 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
36
middleware_test.go
Normal 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)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user