beego 存在三種方式的路由:固定路由、正則路由、自動路由
基礎路由
從 beego 1.2 版本開始支持了基本的 RESTful 函數式路由,應用中的大多數路由都會定義在 routers/router.go
文件中。最簡單的 beego 路由由 URI 和閉包函數組成。
基本 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)
這個函數是關鍵,第一個參數表示路由 URI, 第二個就是你自己實現的 http.Handler
, 注冊之后就會把所有 rpc 作為前綴的請求分發到 http.Handler
中進行處理.
這個函數其實還有第三個參數就是是否是前綴匹配,默認是 false, 如果設置了 true, 那么就會在路由匹配的時候前綴匹配,即 /rpc/user
這樣的也會匹配去運行
路由參數
后面會講到固定路由,正則路由,這些參數一樣適用於上面的這些函數
RESTful Controller 路由
在介紹這三種 beego 的路由實現之前先介紹 RESTful,我們知道 RESTful 是一種目前 API 開發中廣泛采用的形式,beego 默認就是支持這樣的請求方法,也就是用戶 Get 請求就執行 Get 方法,Post 請求就執行 Post 方法。因此默認的路由是這樣 RESTful 的請求方式。
固定路由
固定路由也就是全匹配的路由,如下所示:
beego.Router("/", &controllers.MainController{}) beego.Router("/admin", &admin.UserController{}) beego.Router("/admin/index", &admin.ArticleController{}) beego.Router("/admin/addpkg", &admin.AddController{})
如上所示的路由就是我們最常用的路由方式,一個固定的路由,一個控制器,然后根據用戶請求方法不同請求控制器中對應的方法,典型的 RESTful 方式。
正則路由
為了用戶更加方便的路由設置,beego 參考了 sinatra 的路由實現,支持多種方式的路由:
-
beego.Router(“/api/?:id”, &controllers.RController{})
默認匹配 //例如對於URL”/api/123”可以匹配成功,此時變量”:id”值為”123”
-
beego.Router(“/api/:id”, &controllers.RController{})
默認匹配 //例如對於URL”/api/123”可以匹配成功,此時變量”:id”值為”123”,但URL”/api/“匹配失敗
-
beego.Router(“/api/:id([0-9]+)“, &controllers.RController{})
自定義正則匹配 //例如對於URL”/api/123”可以匹配成功,此時變量”:id”值為”123”
-
beego.Router(“/user/:username([\\w]+)“, &controllers.RController{})
正則字符串匹配 //例如對於URL”/user/astaxie”可以匹配成功,此時變量”:username”值為”astaxie”
-
beego.Router(“/download/*.*”, &controllers.RController{})
*匹配方式 //例如對於URL”/download/file/api.xml”可以匹配成功,此時變量”:path”值為”file/api”, “:ext”值為”xml”
-
beego.Router(“/download/ceshi/*“, &controllers.RController{})
*全匹配方式 //例如對於URL”/download/ceshi/file/api.json”可以匹配成功,此時變量”:splat”值為”file/api.json”
-
beego.Router(“/:id:int”, &controllers.RController{})
int 類型設置方式,匹配 :id為int 類型,框架幫你實現了正則 ([0-9]+)
-
beego.Router(“/:hi:string”, &controllers.RController{})
string 類型設置方式,匹配 :hi 為 string 類型。框架幫你實現了正則 ([\w]+)
-
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
函數,POST
請求執行 Post
函數),如果用戶期望自定義函數名,那么可以使用如下方式:
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)