2

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.

hhprogram
  • 2,809
  • 3
  • 13
  • 25
  • 1
    If you're referring to specific source code, please quote the relevant code in the body of your question rather than linking to it externally. – Adrian Jul 16 '19 at 19:41
  • [`HandlerFunc`](https://godoc.org/github.com/labstack/echo#HandlerFunc) is not a function but a *type*, that's why there is no function definition for it, there is, however, a type definition in the [source code](https://github.com/labstack/echo/blob/master/echo.go#L111) if you're interested. – mkopriva Jul 16 '19 at 19:52

1 Answers1

2

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.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Thanks. I'm still unsure of what happens when a request arrives at `/stats`. Request comes in, how is the middleware `HandlerFunc` `Process` first called? And then let's assume there's a second middleware function to be executed after `Process`. I was wondering how that chain of function calls works. But maybe once I setup my VSCode Go debugger correctly I can just step through it. – hhprogram Jul 16 '19 at 23:38
  • 1
    The router (gin in your case) calls the handler registered for a route. You've wrapped the handler in middleware, so the middleware is what the router is actually calling. Then the middleware calls its parameter, and so on. – Adrian Jul 16 '19 at 23:49