中间件
在gone中,中间件即处理器。通过Before和After方法,你可以在请求前后添加相应的处理:
go
package main
import (
"net/http"
"github.com/cquestor/gone"
)
func HelloHandler(ctx *gone.Context) gone.IResponse {
if ctx.Query("type") == "after" {
return nil
}
return gone.String(http.StatusOK, "Hello!\n")
}
func BeforeHandler(ctx *gone.Context) gone.IResponse {
if ctx.Query("type") == "before" {
return gone.String(http.StatusOK, "from before")
}
return nil
}
func AfterHandler(ctx *gone.Context) gone.IResponse {
return gone.String(http.StatusOK, "from after")
}
func main() {
g := gone.New()
g.Before(BeforeHandler)
g.After(AfterHandler)
g.Get("/hello", HelloHandler)
g.Run()
}
通过访问http://locahost:9999/hello、http://locahost:9999/hello?type=after、http://locahost:9999/hello?type=before即可得到三种不同的结果。
控制器是顺序执行的,只要控制器返回的响应不是nil,就会继续向下执行。
CQuestor