douzen3516 2019-07-16 11:18
浏览 79
已采纳

Golang回声包中间件实现

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.

  • 写回答

1条回答 默认 最新

  • duanlumei5941 2019-07-16 11:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部