英文:
What is the called order of the handlers in martini?
问题
关于golang martini:
- 我们可以使用m.Use()来添加中间件。当然,“中间件处理程序的调用顺序是按照它们被添加的顺序进行的”。
 - 此外,还可以通过路由器像r.Get("/", handler)这样添加处理程序。
 - 有时候,我们还需要在路由器处理程序之后调用一个处理程序。也就是说,在向ResponseWriter写入内容之前调用一个处理程序。
 
那么,这些处理程序的呈现顺序如何确定呢?我在martini的文档中找不到解决方案。
英文:
About golang martini
- We can add middlewares using m.Use(). Of course, "Middleware Handlers are invoked in the order that they are added".
 - In addition, a handler can also be added by router like r.Get("/", handler).
 - Sometimes, we also need a handler be called after the router handler. That is a handler is called before something is written to ResponseWriter.
 
So, how to order of presentation of these handlers? I can not get solution is martini's document.
答案1
得分: 1
如你所说,Martini和其他框架中的中间件按照定义的顺序调用:首先是使用use方法添加的中间件,然后是路由中间件,最后是路由处理函数。
以下是Martini文档中给出的一个中间件示例:
// 在请求前后记录日志
m.Use(func(c martini.Context, log *log.Logger){
    log.Println("before a request")
    c.Next()
    log.Println("after a request")
})
根据这个示例,如果你有中间件A和B以及路由R,那么调用链将类似于:
func A() {
    // 在B之前执行的操作
    func B() {
        // 在R之前执行的操作
        func R() {
            // 在R中执行的操作
        }()
        // 在R之后执行的操作
    }()
    // 在B之后执行的操作
}
因此,根据你的需求,在Next()调用之前或之后的中间件中添加代码。
英文:
As you said, middlewares in Martini and others are called in the order they are defined: first the ones added with use, then the route middlewares, then the route handler.
Here is the middleware example given by the martini documentation:
// log before and after a request
m.Use(func(c martini.Context, log *log.Logger){
    log.Println("before a request")
    c.Next()
    log.Println("after a request")
})
According to this, if you have middlewares A and B and the route R, then the call chain will be something like that:
func A() {
    // Do things before B
    func B() {
        // Do things before R
        
        func R() {
            // Do things in R
        } ()
        
        // Do things after R
    }()
    // Do things after B
}
So depending of what you need, you will need to add code in a middleware before or after the Next()  call.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论