gomartini

What is the called order of the handlers in martini?


About golang martini

So, how to order of presentation of these handlers? I can not get solution is martini's document.


Solution

  • 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.