From c1cac160737b70b0afd5e2fb725f7e31d38e583a Mon Sep 17 00:00:00 2001 From: xiemengjun Date: Sun, 16 Dec 2012 00:34:45 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E5=92=8Crouter=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 23 +++++++++++++++++++++++ beego.go | 15 +++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/README.md b/README.md index 2892dc01..433fe720 100644 --- a/README.md +++ b/README.md @@ -72,5 +72,28 @@ this will serve any files in /static, including files in subdirectories. For exa ## Filters / Middleware ============ +You can apply filters to routes, which is useful for enforcing security, redirects, etc. +You can, for example, filter all request to enforce some type of security: + + var FilterUser = func(w http.ResponseWriter, r *http.Request) { + if r.URL.User == nil || r.URL.User.Username() != "admin" { + http.Error(w, "", http.StatusUnauthorized) + } + } + + beego.BeeApp.Filter(FilterUser) + +You can also apply filters only when certain REST URL Parameters exist: + + beego.BeeApp.RegisterController("/:id([0-9]+)", &admin.EditController{}) + beego.BeeApp.FilterParam("id", func(rw http.ResponseWriter, r *http.Request) { + ... + }) + +also You can apply filters only when certain prefix URL path exist: + + beego.BeeApp.FilterPrefixPath("/admin", func(rw http.ResponseWriter, r *http.Request) { + … auth + }) \ No newline at end of file diff --git a/beego.go b/beego.go index c92c750f..99bffbc9 100644 --- a/beego.go +++ b/beego.go @@ -93,6 +93,21 @@ func (app *App) RegisterController(path string, c ControllerInterface) *App { return app } +func (app *App) Filter(filter http.HandlerFunc) *App { + app.Handlers.Filter(filter) + return app +} + +func (app *App) FilterParam(param string, filter http.HandlerFunc) *App { + app.Handlers.FilterParam(param, filter) + return app +} + +func (app *App) FilterPrefixPath(path string, filter http.HandlerFunc) *App { + app.Handlers.FilterParam(path, filter) + return app +} + func (app *App) SetViewsPath(path string) *App { ViewsPath = path return app