From 4ea052128b0008aa878b5472ef27053e3693b2d7 Mon Sep 17 00:00:00 2001 From: Roman Serikov Date: Fri, 15 Oct 2021 02:31:15 +0300 Subject: [PATCH] Changed Mixed() middleware to get variadic number of input mws --- middleware.go | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/middleware.go b/middleware.go index d2a0f98..291b200 100644 --- a/middleware.go +++ b/middleware.go @@ -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 } } }