Skip to content

Commit

Permalink
Added middleware for http server
Browse files Browse the repository at this point in the history
  • Loading branch information
dobyte committed Aug 1, 2024
1 parent 7181d39 commit b7c07f6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
18 changes: 15 additions & 3 deletions component/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions component/http/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type options struct {
registry registry.Registry // 服务注册器
transporter transport.Transporter // 消息传输器
swagger Swagger // swagger配置
middlewares []any // 中间件
}

type Swagger struct {
Expand Down Expand Up @@ -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 }
}
2 changes: 0 additions & 2 deletions component/http/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit b7c07f6

Please sign in to comment.