hhprogram
hhprogram

Reputation: 3127

Golang echo package middleware implementation

I'm learning Go and was going through this example : echo middleware example. I wanted to do a deep dive to understand what was going on when we call next(c) in the function middleware function Process().

Looking at the main() I understand we append the Process() function to the echo Context object's list of middleware functions via the Use() call. However, looking at the echo source code I'm unsure how the next(c) call in the Process() function in the middleware example looks through all of the context's middleware functions. Couple things that I cannot seem to find even after searching the source code:

(1) Where is the function definition for echo.HandlerFunc being defined? I see WrapHandler but that's exported and not used in echo.go so I'm confused what happens when next(c) gets called what line of code in echo.go source code we jump to.

(2) It looks like the loop happens when calling applyMiddleware as that seems to loop through all the middleware functions saved in the Context's list of middleware functions but I don't see how that method is called unless you call the exported WrapMiddleware function or ServeHTTP etc.

Upvotes: 2

Views: 3090

Answers (1)

Adrian
Adrian

Reputation: 46413

next(c) doesn't loop through anything. next is a variable received as a function parameter, which contains a function. next(c) calls that function. In practice, it is the next part of the chain - which might be the next middleware, or might be the final request handler. When the func that Process returns is called, that itself might have been called as next by the middleware before it.

There's no magic involved, and nothing hidden within the library It's just a chain of function calls.

Upvotes: 2

Related Questions