Page:
Handler
Pages
Actions
Basicauth
Binding
Captcha
Compress
Context
Debug
Dispatch
ErrHandler
Events
Flash
Forms
Group
Handler
Home
Injection
Logger
Params
QuickStart
Recovery
Renders
Return
Router
Session
Static
Tango
Tpongo2
Xsrf
ZH_Actions
ZH_Basicauth
ZH_Binding
ZH_Captcha
ZH_Compress
ZH_Context
ZH_Debug
ZH_Dispatch
ZH_ErrHandler
ZH_Events
ZH_Flash
ZH_Forms
ZH_Group
ZH_HOME
ZH_Handler
ZH_Injection
ZH_Logger
ZH_Params
ZH_Recovery
ZH_Renders
ZH_Return
ZH_Router
ZH_Session
ZH_Static
ZH_Tango
ZH_Tpongo2
ZH_Xsrf
10
Handler
Lunny Xiao edited this page 2015-01-05 21:46:23 +08:00
Table of Contents
Handler
Handler is the middleware of tango. In tango, almost everything will be Handler. Write your Handlers are easy.
type Handler interface {
Handle(*tango.Context)
}
For example:
func MyHandler() tango.HandlerFunc {
return func(ctx *tango.Context) {
fmt.Println("this is my first tango handler")
ctx.Next()
}
}
t := tango.Classic()
t.Use(MyHandler())
t.Run()
Another form:
type HelloHandler struct {}
func (HelloHandler) Handle(ctx *tango.Context) {
fmt.Println("before")
ctx.Next()
fmt.Println("after")
}
t := tango.Classic()
t.Use(new(HelloHandler))
t.Run()
Also, you can directly use a function as your handler:
tg.Use(func(ctx *tango.Context){
fmt.Println("before")
ctx.Next()
fmt.Println("after")
})
For compitable, tango supports your old form handler via UseHandler()
tg.UseHandler(http.Handler(func(resp http.ResponseWriter, req *http.Request) {
}))
Old handler will be called before action invoked.
Call stack
When a request call by tango, below is the call stack:
tango.ServeHttp
|--Handler1
|--Handler2
|-- ...HandlerN
|---Action(If matched)
...HandlerN--|
Handler2 ----|
Handler1--|
(end)--|
In your Handler, all codes before ctx.Next()
will be called before Action(If matched) will be called. All codes after ctx.Next()
will be called after Action(If matched) called.
Of course, If your handler DO NOT call ctx.Next()
. All call stack after will be not executed.