begoo——路由設定
路由本質是URL與要為該URL呼叫的檢視函式之間的對映表,其實就是你定義的使用那個URL呼叫那段程式碼的關係對應表。
首先看一下最簡單的路由:
package routers import ( "pro1/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) }
以及對應的控制器函式:
package controllers import ( "github.com/astaxie/beego" ) type MainController struct { beego.Controller } func (c *MainController) Get(){ c.Data["Website"] = "beego.me" c.Data["Email"] = "[email protected]" c.TplName = "index.tpl" }
基礎路由
從beego1.2版本開始支援基本的RESTful函式式路由,應用中大多數路由都會定義在routers/router.go檔案中。
基本GET路由
beego.Get("/",func(ctx *context.Context){ ctx.Output.Body([]byte("hello world")) })
基本POST路由
beego.Post("/alice",func(ctx *context.Context){ ctx.Output.Body([]byte("bob")) })
註冊一個可以響應任何HTTP的路由
beego.Any("/foo",func(ctx *context.Context){ ctx.Output.Body([]byte("bar")) })
所有的支援的基礎函式如下所示
- beego.Get(router, beego.FilterFunc)
- beego.Post(router, beego.FilterFunc)
- beego.Put(router, beego.FilterFunc)
- beego.Patch(router, beego.FilterFunc)
- beego.Head(router, beego.FilterFunc)
- beego.Options(router, beego.FilterFunc)
- beego.Delete(router, beego.FilterFunc)
- beego.Any(router, beego.FilterFunc)
支援自定義的handler實現
有時候我們已經實現了一些rpc的應用,但是想要整合到beego中,或者其它的httpserver應用整合到beego中來,現在可以很方便的整合。
s := rpc.NewServer() s.RegisterCodec(json.NewCodec(), "application/json") s.RegisterService(new(HelloService), "") beego.Handler("/rpc", s)
beego.Handler(router, http.Handler)這個函式是關鍵,第一個引數表示路由URL,第二個就是你自己實現的http.Handler,註冊時候就會把所有rpc作為字首的請求分發到http.handler中進行處理。
這個函式其實還有第三個引數就是是否是字首匹配,預設是false,如果這隻了true,那麼就會在路由匹配的時候字首匹配,即/rpc/user這樣的也會匹配去執行。
固定路由
固定路由也就是全匹配的路由,如下所示:
beego.Router("/", &controllers.MainController{}) beego.Router("/admin", &admin.UserController{}) beego.Router("/admin/index", &admin.ArticleController{}) beego.Router("/admin/addpkg", &admin.AddController{})
如上所示的路由就是我們最常用的路由方式,一個固定的路由,一個控制器,然後根據使用者請求方法的不同請求控制器中對應的方法。
正則路由
為了使用者更加方便地路由設定,beego參考了sinatra的路由實現,支援多種方式的路由:
(1)beego.Router(“/api/?:id”, &controllers.RController{})
?表示匹配0個或1個任意字元,例如對於URL”/api/123”可以匹配成功,此時變數”:id”值為”123”。
(2)beego.Router(“/api/:id”, &controllers.RController{})
例如對於URL”/api/123”可以匹配成功,此時變數”:id”值為”123”,但URL”/api/“匹配失敗。
(3)beego.Router(“/api/:id([0-9]+)“, &controllers.RController{})
+表示匹配一個或多個任意字元,例如對於URL”/api/123”可以匹配成功,此時變數”:id”值為”123”。
(4)beego.Router(“/user/:username([\\w]+)“, &controllers.RController{})
\w表示匹配數字、字母和下劃線,例如對於URL”/user/astaxie”可以匹配成功,此時變數”:username”值為”astaxie”
(5)beego.Router(“/download/*.*”, &controllers.RController{})
例如對於URL”/download/file/api.xml”可以匹配成功,此時變數”:path”值為”file/api”, “:ext”值為”xml”
(6)beego.Router(“/download/ceshi/*“, &controllers.RController{})
例如對於URL”/download/ceshi/file/api.json”可以匹配成功,此時變數”:splat”值為”file/api.json”
(7)beego.Router(“/:id:int”, &controllers.RController{})
int 型別設定方式,匹配 :id為int 型別,框架幫你實現了正則 ([0-9]+)
(8)beego.Router(“/:hi:string”, &controllers.RController{})
string 型別設定方式,匹配 :hi 為 string 型別。框架幫你實現了正則 ([\w]+)
(9)beego.Router(“/cms_:id([0-9]+).html”, &controllers.CmsController{})
帶有字首的自定義正則 //匹配 :id 為正則型別。匹配 cms_123.html 這樣的 url :id = 123
可以在Controller中通過如下方式獲取上面的變數。
this.Ctx.Input.Param(":id") this.Ctx.Input.Param(":username") this.Ctx.Input.Param(":splat") this.Ctx.Input.Param(":path") this.Ctx.Input.Param(":ext")
自定義方法及RESTful規則
上面列舉的是預設的請求方法名(請求的method和函式名一致,例如Get請求執行Get函式),如果使用者期望自定義函式名,那麼可以使用如下方式:
beego.Router("/",&IndexController{},"*:Index")
使用第三個引數,第三個引數就是用來設定對應method到函式名,定義如下:
- *表示任意的method都執行該函式
- 使用httpmethod:funcname格式來顯式
- 多個不同的格式使用;分割
- 多個method對應同一個funcname,method之間通過“,”來分割
以下是一個RESTful的設計示例:
beego.Router("/api/list",&RestController{},"*:ListFood") beego.Router("/api/create",&RestController{},"post:CreateFood") beego.Router("/api/update",&RestController{},"put:UpdateFood") beego.Router("/api/delete",&RestController{},"delete:DeleteFood")
以下是多個HTTP Method指向同一個函式的示例:
beego.Router("/api",&RestController{},"get,post:ApiFunc")
以下是不同的method對應不同的函式,通過“;”進行分割的示例:
beego.Router("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
可用的HTTP Method:
- *: 包含以下所有的函式
- get: GET 請求
- post: POST 請求
- put: PUT 請求
- delete: DELETE 請求
- patch: PATCH 請求
- options: OPTIONS 請求
- head: HEAD 請求
如果同時存在*和對應的HTTP Method,那麼優先執行HTTP Method方法,例如同時註冊瞭如下所示的路由:
beego.Router("/simple",&SimpleController{},"*:AllFunc;post:PostFunc")
那麼執行Post請求的時候,執行PostFunc而不執行AllFunc。
自定義函式的路由預設不支援RESTful方法,也就是如果你設定了beego.Router("/api",&RestController{},"post:ApiFunc")這樣的路由,如果請求的方法是POST,那麼不會預設去執行Post函式。
自動匹配
使用者首先需要把需要路由的控制器註冊到自動路由中:
beego.AutoRouter(&controllers.ObjectController{})
那麼beego就會通過反射獲取該結構體中所有的實現方法,你可以通過如下方式訪問到對應的方法中:
/object/login 呼叫 ObjectController 中的 Login 方法 /object/logout 呼叫 ObjectController 中的 Logout 方法
除了字首兩個 /:controller/:method
的匹配之外,剩下的 url beego 會幫你自動化解析為引數,儲存在 this.Ctx.Input.Params
當中:
/object/blog/2013/09/12 呼叫 ObjectController 中的 Blog 方法,引數如下:map[0:2013 1:09 2:12]
方法名在內部是儲存了使用者設定的,例如 Login,url 匹配的時候都會轉化為小寫,所以,/object/LOGIN
這樣的 url
也一樣可以路由到使用者定義的 Login
方法中。
現在已經可以通過自動識別出來下面類似的所有 url,都會把請求分發到 controller
的 simple
方法:
/controller/simple /controller/simple.html /controller/simple.json /controller/simple.xml
可以通過 this.Ctx.Input.Param(":ext")
獲取字尾名。
註解路由
從beego 1.3版本開始支援註解路由,使用者無需在router中註冊路由,只需要include相應的controller,
然後在controller的method方法上面寫上router註釋(//@router)就可以了,詳細的使用請看下面的例子:
// CMS API type CMSController struct { beego.Controller } func (c *CMSController) URLMapping() { c.Mapping("StaticBlock", c.StaticBlock) c.Mapping("AllBlock", c.AllBlock) } // @router /staticblock/:key [get] func (this *CMSController) StaticBlock() { } // @router /all/:key [get] func (this *CMSController) AllBlock() { }
可以在router.go中通過如下方式註冊路由:
beego.Include(&CMSController{})
beego自動會進行原始碼分析,注意只會在dev模式下進行生成,生成的路由放在“/routers/commentsRouter.go” 檔案中。
這樣上面的路由就支援瞭如下的路由:
- GET /staticblock/:key
- GET /all/:key
其實效果和自己通過 Router 函式註冊是一樣的:
beego.Router("/staticblock/:key", &CMSController{}, "get:StaticBlock") beego.Router("/all/:key", &CMSController{}, "get:AllBlock")
同時大家注意到新版本里面增加了 URLMapping 這個函式,這是新增加的函式,使用者如果沒有進行註冊,那麼就會通過反射來執行對應的函式,
如果註冊了就會通過 interface 來進行執行函式,效能上面會提升很多。
namespace
//初始化 namespace ns := beego.NewNamespace("/v1", beego.NSCond(func(ctx *context.Context) bool { if ctx.Input.Domain() == "api.beego.me" { return true } return false }), beego.NSBefore(auth), beego.NSGet("/notallowed", func(ctx *context.Context) { ctx.Output.Body([]byte("notAllowed")) }), beego.NSRouter("/version", &AdminController{}, "get:ShowAPIVersion"), beego.NSRouter("/changepassword", &UserController{}), beego.NSNamespace("/shop", beego.NSBefore(sentry), beego.NSGet("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("notAllowed")) }), ), beego.NSNamespace("/cms", beego.NSInclude( &controllers.MainController{}, &controllers.CMSController{}, &controllers.BlockController{}, ), ), ) //註冊 namespace beego.AddNamespace(ns)
上面這個程式碼支援瞭如下這樣的請求 URL
- GET /v1/notallowed
- GET /v1/version
- GET /v1/changepassword
- POST /v1/changepassword
- GET /v1/shop/123
- GET /v1/cms/ 對應 MainController、CMSController、BlockController 中得註解路由
而且還支援前置過濾,條件判斷,無限巢狀 namespace
namespace 的介面如下:
-
NewNamespace(prefix string, funcs …interface{})
初始化 namespace 物件,下面這些函式都是 namespace 物件的方法,但是強烈推薦使用 NS 開頭的相應函式註冊,因為這樣更容易通過 gofmt 工具看的更清楚路由的級別關係
-
NSCond(cond namespaceCond)
支援滿足條件的就執行該 namespace, 不滿足就不執行
-
NSBefore(filiterList …FilterFunc)
-
NSAfter(filiterList …FilterFunc)
上面分別對應 beforeRouter 和 FinishRouter 兩個過濾器,可以同時註冊多個過濾器
-
NSInclude(cList …ControllerInterface)
-
NSRouter(rootpath string, c ControllerInterface, mappingMethods …string)
-
NSGet(rootpath string, f FilterFunc)
-
NSPost(rootpath string, f FilterFunc)
-
NSDelete(rootpath string, f FilterFunc)
-
NSPut(rootpath string, f FilterFunc)
-
NSHead(rootpath string, f FilterFunc)
-
NSOptions(rootpath string, f FilterFunc)
-
NSPatch(rootpath string, f FilterFunc)
-
NSAny(rootpath string, f FilterFunc)
-
NSHandler(rootpath string, h http.Handler)
-
NSAutoRouter(c ControllerInterface)
-
NSAutoPrefix(prefix string, c ControllerInterface)
上面這些都是設定路由的函式,詳細的使用和上面 beego 的對應函式是一樣的
-
NSNamespace(prefix string, params …innnerNamespace)
巢狀其他 namespace
ns := beego.NewNamespace("/v1", beego.NSNamespace("/shop", beego.NSGet("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("shopinfo")) }), ), beego.NSNamespace("/order", beego.NSGet("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("orderinfo")) }), ), beego.NSNamespace("/crm", beego.NSGet("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("crminfo")) }), ), )
下面這些函式都是屬於 *Namespace 物件的方法:不建議直接使用,當然效果和上面的 NS 開頭的函式是一樣的,只是上面的方式更優雅,寫出來的程式碼更容易看得懂
-
Cond(cond namespaceCond)
支援滿足條件的就執行該 namespace, 不滿足就不執行,例如你可以根據域名來控制 namespace
-
Filter(action string, filter FilterFunc)
action 表示你需要執行的位置, before 和 after 分別表示執行邏輯之前和執行邏輯之後的 filter
-
Router(rootpath string, c ControllerInterface, mappingMethods …string)
-
AutoRouter(c ControllerInterface)
-
AutoPrefix(prefix string, c ControllerInterface)
-
Get(rootpath string, f FilterFunc)
-
Post(rootpath string, f FilterFunc)
-
Delete(rootpath string, f FilterFunc)
-
Put(rootpath string, f FilterFunc)
-
Head(rootpath string, f FilterFunc)
-
Options(rootpath string, f FilterFunc)
-
Patch(rootpath string, f FilterFunc)
-
Any(rootpath string, f FilterFunc)
-
Handler(rootpath string, h http.Handler)
上面這些都是設定路由的函式,詳細的使用和上面 beego 的對應函式是一樣的
-
Namespace(ns …*Namespace)
更多的例子程式碼:
//APIS ns := beego.NewNamespace("/api", //此處正式版時改為驗證加密請求 beego.NSCond(func(ctx *context.Context) bool { if ua := ctx.Input.Request.UserAgent(); ua != "" { return true } return false }), beego.NSNamespace("/ios", //CRUD Create(建立)、Read(讀取)、Update(更新)和Delete(刪除) beego.NSNamespace("/create", // /api/ios/create/node/ beego.NSRouter("/node", &apis.CreateNodeHandler{}), // /api/ios/create/topic/ beego.NSRouter("/topic", &apis.CreateTopicHandler{}), ), beego.NSNamespace("/read", beego.NSRouter("/node", &apis.ReadNodeHandler{}), beego.NSRouter("/topic", &apis.ReadTopicHandler{}), ), beego.NSNamespace("/update", beego.NSRouter("/node", &apis.UpdateNodeHandler{}), beego.NSRouter("/topic", &apis.UpdateTopicHandler{}), ), beego.NSNamespace("/delete", beego.NSRouter("/node", &apis.DeleteNodeHandler{}), beego.NSRouter("/topic", &apis.DeleteTopicHandler{}), ) ), ) beego.AddNamespace(ns)