feat: rest.WithChain to replace builtin middlewares (#2033)

* feat: rest.WithChain to replace builtin middlewares

* chore: add comments

* chore: refine code
This commit is contained in:
Kevin Wan
2022-06-19 17:41:33 +08:00
committed by GitHub
parent 50f16e2892
commit 47c49de94e
6 changed files with 322 additions and 98 deletions

View File

@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"os"
"strings"
"sync/atomic"
"testing"
"time"
@@ -16,6 +17,7 @@ import (
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/rest/chain"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/router"
)
@@ -435,3 +437,44 @@ func TestValidateSecret(t *testing.T) {
validateSecret("short")
})
}
func TestServer_WithChain(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(chain.New(middleware1(), middleware2())))
server.AddRoutes(
[]Route{
{
Method: http.MethodGet,
Path: "/",
Handler: func(_ http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&called, 1)
},
},
},
)
rt := router.NewRouter()
assert.Nil(t, server.ngin.bindRoutes(rt))
req, err := http.NewRequest(http.MethodGet, "/", nil)
assert.Nil(t, err)
rt.ServeHTTP(httptest.NewRecorder(), req)
assert.Equal(t, int32(5), atomic.LoadInt32(&called))
}