Skip to content

Commit

Permalink
Merge pull request #13 from RomanSerikov/feature/variadic-param-middl…
Browse files Browse the repository at this point in the history
…ewares

Changed Mixed() middleware to get variadic number of input mws
  • Loading branch information
LukaszKokot authored Oct 15, 2021
2 parents 30d79cc + 4ea0521 commit f0784f3
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 f0784f3

Please sign in to comment.