What is the called order of the handlers in martini?

351 views Asked by At

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

There are 1 answers

0
Elwinar On BEST ANSWER

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.