Skip to content

Commit

Permalink
Changed Mixed() middleware to get variadic number of input mws
Browse files Browse the repository at this point in the history
  • Loading branch information
RomanSerikov committed Oct 14, 2021
1 parent 30d79cc commit 4ea0521
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,39 @@ import (
echo "github.com/labstack/echo/v4"
)

// Mixed returns a single middleware function composed of the two middlewares.
// Mixed returns a single middleware function composed of the middlewares.
// Upon being called, it is internally going to call the first middleware, and if there
// is no error, return immediately with the answer.
//
// Otherwise, it is going to call the second middleware, and return their response.
func Mixed(preserveKeys []string) func(handler1, handler2 echo.MiddlewareFunc) echo.MiddlewareFunc {
return func(handler1, handler2 echo.MiddlewareFunc) echo.MiddlewareFunc {
// Otherwise, it is going to call the next middlewares, and return their response.
func Mixed(preserveKeys []string) func(handlers ...echo.MiddlewareFunc) echo.MiddlewareFunc {
return func(handlers ...echo.MiddlewareFunc) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
a1 := handler1(next)
a2 := handler2(next)
var tempContext echo.Context

return func(c echo.Context) error {
tempContext := copyContext(c, preserveKeys)
defer tempContext.Echo().ReleaseContext(tempContext)
if a1(tempContext) == nil {
copyResponse(c, tempContext, preserveKeys)
var err error

for _, handler := range handlers {
tempContext = copyContext(c, preserveKeys)
defer tempContext.Echo().ReleaseContext(tempContext)

err = handler(next)(tempContext)
if err == nil {
copyResponse(c, tempContext, preserveKeys)

return nil
return nil
}
}

// Try the second middleware
err := a2(c)
if err != nil {
// Return the first middleware error
copyResponse(c, tempContext, preserveKeys)
c.Response().WriteHeader(tempContext.Response().Status)

return err
}
return err

return nil
}
}
}
Expand Down

0 comments on commit 4ea0521

Please sign in to comment.