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

@@ -8,6 +8,7 @@ import (
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/chain"
"github.com/zeromicro/go-zero/rest/handler"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal/cors"
@@ -95,13 +96,6 @@ func (s *Server) Use(middleware Middleware) {
s.ngin.use(middleware)
}
// DisableDefaultMiddlewares returns a RunOption that disables the builtin middlewares.
func DisableDefaultMiddlewares() RunOption {
return func(svr *Server) {
svr.ngin.disableDefaultMiddlewares = true
}
}
// ToMiddleware converts the given handler to a Middleware.
func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
return func(handle http.HandlerFunc) http.HandlerFunc {
@@ -109,6 +103,14 @@ func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
}
}
// WithChain returns a RunOption that uses the given chain to replace the default chain.
// JWT auth middleware and the middlewares that added by svr.Use() will be appended.
func WithChain(chn chain.Chain) RunOption {
return func(svr *Server) {
svr.ngin.chain = chn
}
}
// WithCors returns a func to enable CORS for given origin, or default to all origins (*).
func WithCors(origin ...string) RunOption {
return func(server *Server) {