Skip to content

Commit

Permalink
chore: implements use and uses
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagozs committed May 25, 2024
1 parent fc1ef98 commit 9efbbcd
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 4 deletions.
16 changes: 12 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"time"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

// Kind represents the type of router group
Expand Down Expand Up @@ -134,9 +133,10 @@ func NewServer(opts ...Options) (*Server, error) {

e := echo.New()

e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORS())
// e.Use(middleware.Logger())
// e.Use(middleware.Recover())
// e.Use(middleware.CORS())

e.HideBanner = true

return &Server{
Expand All @@ -147,6 +147,14 @@ func NewServer(opts ...Options) (*Server, error) {
}, nil
}

func (s *Server) Use(middleware MiddlewareFunc) {
s.echo.Use(middleware)
}

func (s *Server) Uses(middlewares ...MiddlewareFunc) {
s.echo.Use(middlewares...)
}

// NewContext creates a new Echo context
func (s *Server) NewContext(req *http.Request, w http.ResponseWriter) Context {
return s.echo.NewContext(req, w)
Expand Down
62 changes: 62 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1131,3 +1131,65 @@ func TestRoutesWithMultiGroupWithBasicAuth(t *testing.T) {
})
}
}

func TestWithUse(t *testing.T) {
server, _ := NewServer()
rr := NewRouters()
rr.AddRouter("/test", map[string]HandlerFunc{
http.MethodGet: func(c Context) error {
return c.String(http.StatusOK, "test passed")
},
})

middlewareA := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return next(c)
}
}

_ = server.RegisterRouters(ROOT, rr)
server.Use(middlewareA)

e := server.GetEcho()

req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "test passed", rec.Body.String())
}

func TestWithUses(t *testing.T) {
server, _ := NewServer()
rr := NewRouters()
rr.AddRouter("/test", map[string]HandlerFunc{
http.MethodGet: func(c Context) error {
return c.String(http.StatusOK, "test passed")
},
})

middlewareA := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return next(c)
}
}

middlewareB := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return next(c)
}
}

_ = server.RegisterRouters(ROOT, rr)
server.Uses(middlewareA, middlewareB)

e := server.GetEcho()

req := httptest.NewRequest(http.MethodGet, "/test", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "test passed", rec.Body.String())
}

0 comments on commit 9efbbcd

Please sign in to comment.