add user middleware chain function (#1913)

* add user middleware chain function

* fix staticcheck SA4006

* chang code Implementation style

Co-authored-by: kemq1 <kemq1@spdb.com.cn>
This commit is contained in:
magickeha
2022-06-18 18:45:47 +08:00
committed by GitHub
parent 9b6e4c440c
commit 6976ba7e13
3 changed files with 90 additions and 13 deletions

View File

@@ -229,6 +229,44 @@ func TestEngine_checkedMaxBytes(t *testing.T) {
}
}
func TestEngine_checkedChain(t *testing.T) {
var called int32
middleware1 := func() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&called, 1)
next.ServeHTTP(w, r)
atomic.AddInt32(&called, 1)
})
}
}
middleware2 := func() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&called, 1)
next.ServeHTTP(w, r)
atomic.AddInt32(&called, 1)
})
}
}
server := MustNewServer(RestConf{}, WithChain(middleware1(), middleware2()))
server.router = chainRouter{}
server.AddRoutes(
[]Route{
{
Method: http.MethodGet,
Path: "/",
Handler: func(_ http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&called, 1)
},
},
},
)
server.ngin.bindRoutes(chainRouter{})
assert.Equal(t, int32(5), atomic.LoadInt32(&called))
}
func TestEngine_notFoundHandler(t *testing.T) {
logx.Disable()
@@ -343,3 +381,19 @@ func (m mockedRouter) SetNotFoundHandler(_ http.Handler) {
func (m mockedRouter) SetNotAllowedHandler(_ http.Handler) {
}
type chainRouter struct{}
func (c chainRouter) ServeHTTP(_ http.ResponseWriter, _ *http.Request) {
}
func (c chainRouter) Handle(_, _ string, handler http.Handler) error {
handler.ServeHTTP(nil, nil)
return nil
}
func (c chainRouter) SetNotFoundHandler(_ http.Handler) {
}
func (c chainRouter) SetNotAllowedHandler(_ http.Handler) {
}