From b7c07f64d1e3a503dac7015cc95a3b01cbf1aba6 Mon Sep 17 00:00:00 2001 From: fuxiao <576101059@qq.com> Date: Thu, 1 Aug 2024 20:49:40 +0800 Subject: [PATCH] Added middleware for http server --- component/http/http.go | 18 +++++++++++++++--- component/http/options.go | 6 ++++++ component/http/router.go | 2 -- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/component/http/http.go b/component/http/http.go index 9fc30ca..34f566d 100644 --- a/component/http/http.go +++ b/component/http/http.go @@ -8,6 +8,7 @@ import ( xnet "github.com/dobyte/due/v2/core/net" "github.com/dobyte/due/v2/log" "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/middleware/cors" "github.com/gofiber/fiber/v3/middleware/logger" "github.com/gofiber/fiber/v3/middleware/recover" "strings" @@ -29,11 +30,22 @@ func NewHttp(opts ...Option) *Http { h := &Http{} h.opts = o h.proxy = newProxy(h) - h.app = fiber.New(fiber.Config{ - ServerHeader: o.name, - }) + h.app = fiber.New(fiber.Config{ServerHeader: o.name}) h.app.Use(logger.New()) h.app.Use(recover.New()) + h.app.Use(cors.New()) + + for i := range o.middlewares { + switch handler := o.middlewares[i].(type) { + case Handler: + h.app.Use(func(ctx fiber.Ctx) error { + return handler(&context{Ctx: ctx}) + }) + case fiber.Handler: + h.app.Use(handler) + } + } + if h.opts.swagger.Enable { h.app.Use(swagger.New(swagger.Config{ Title: h.opts.swagger.Title, diff --git a/component/http/options.go b/component/http/options.go index 906d056..35e398e 100644 --- a/component/http/options.go +++ b/component/http/options.go @@ -29,6 +29,7 @@ type options struct { registry registry.Registry // 服务注册器 transporter transport.Transporter // 消息传输器 swagger Swagger // swagger配置 + middlewares []any // 中间件 } type Swagger struct { @@ -91,3 +92,8 @@ func WithTransporter(transporter transport.Transporter) Option { func WithSwagger(swagger Swagger) Option { return func(o *options) { o.swagger = swagger } } + +// WithMiddlewares 设置中间件 +func WithMiddlewares(middlewares ...any) Option { + return func(o *options) { o.middlewares = middlewares } +} diff --git a/component/http/router.go b/component/http/router.go index 4574018..22afd68 100644 --- a/component/http/router.go +++ b/component/http/router.go @@ -6,8 +6,6 @@ import ( type Handler func(ctx Context) error -type MiddlewareHandler func(ctx Context) error - type Router interface { // Get 添加GET请求处理器 Get(path string, handler Handler, middlewares ...Handler) Router