web框架中逻族,路由是重要的一環(huán),對于beego的路由配置如何蝇摸?
讓我們從入口文件先分析起來吧:
package main
import (
_ "web/routers"
"github.com/astaxie/beego"
)
func main() {
beego.Run()
}
我們看到 main 函數(shù)是入口函數(shù)夹孔,但是我們知道 Go 的執(zhí)行過程是如下圖所示的方式:
這里我們就看到了我們引入了一個包 _ "web/routers"
,這個包只引入執(zhí)行了里面的 init 函數(shù),那么讓我們看看這個里面做了什么事情:
package routers
import (
"web/controllers"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/", &controllers.MainController{})
}
路由包里面我們看到執(zhí)行了路由注冊 beego.Router
, 這個函數(shù)的功能是映射 URL 到 controller琅轧,第一個參數(shù)是 URL (用戶請求的地址)伍绳,這里我們注冊的是 /
,也就是我們訪問的不帶任何參數(shù)的 URL鹰晨,第二個參數(shù)是對應的 Controller墨叛,也就是我們即將把請求分發(fā)到那個控制器來執(zhí)行相應的邏輯,我們可以執(zhí)行類似的方式注冊如下路由:
beego.Router("/user", &controllers.UserController{})
看一下這個Router
的源碼:
func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App {
BeeApp.Handlers.Add(rootpath, c, mappingMethods...)
return BeeApp
}
路由設置
beego 存在三種方式的路由:固定路由模蜡、正則路由漠趁、自動路由,接下來詳細的講解如何使用這三種路由忍疾。
基礎路由
從 beego 1.2 版本開始支持了基本的 RESTful 函數(shù)式路由,應用中的大多數(shù)路由都會定義在 routers/router.go
文件中闯传。最簡單的 beego 路由由 URI 和閉包函數(shù)組成。
基本 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"))
})
所有的支持的基礎函數(shù)如下所示
- 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 實現(xiàn)
有些時候我們已經實現(xiàn)了一些 rpc 的應用,但是想要集成到 beego 中,或者其他的 httpserver 應用,集成到 beego 中來.現(xiàn)在可以很方便的集成:
s := rpc.NewServer()
s.RegisterCodec(json.NewCodec(), "application/json")
s.RegisterService(new(HelloService), "")
beego.Handler("/rpc", s)
beego.Handler(router, http.Handler)
這個函數(shù)是關鍵,第一個參數(shù)表示路由 URI, 第二個就是你自己實現(xiàn)的 http.Handler
, 注冊之后就會把所有 rpc 作為前綴的請求分發(fā)到 http.Handler
中進行處理.
這個函數(shù)其實還有第三個參數(shù)就是是否是前綴匹配,默認是 false, 如果設置了 true, 那么就會在路由匹配的時候前綴匹配,即 /rpc/user
這樣的也會匹配去運行
路由參數(shù)
后面會講到固定路由,正則路由,這些參數(shù)一樣適用于上面的這些函數(shù)
RESTful Controller 路由
在介紹這三種 beego 的路由實現(xiàn)之前先介紹 RESTful卤妒,我們知道 RESTful 是一種目前 API 開發(fā)中廣泛采用的形式甥绿,beego 默認就是支持這樣的請求方法,也就是用戶 Get 請求就執(zhí)行 Get 方法则披,Post 請求就執(zhí)行 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 的路由實現(xiàn)承璃,支持多種方式的路由:
-
beego.Router(“/api/?:id”, &controllers.RController{})
默認匹配 //匹配 /api/123 :id = 123 可以匹配 /api/ 這個URL
-
beego.Router(“/api/:id”, &controllers.RController{})
默認匹配 //匹配 /api/123 :id = 123 不可以匹配 /api/ 這個URL
-
beego.Router(“/api/:id([0-9]+)“, &controllers.RController{})
自定義正則匹配 //匹配 /api/123 :id = 123
-
beego.Router(“/user/:username([\w]+)“, &controllers.RController{})
正則字符串匹配 //匹配 /user/astaxie :username = astaxie
-
beego.Router(“/download/.”, &controllers.RController{})
*匹配方式 //匹配 /download/file/api.xml :path= file/api :ext=xml
-
beego.Router(“/download/ceshi/*“, &controllers.RController{})
*全匹配方式 //匹配 /download/ceshi/file/api.json :splat=file/api.json
-
beego.Router(“/:id:int”, &controllers.RController{})
int 類型設置方式,匹配 :id為int 類型蚌本,框架幫你實現(xiàn)了正則 ([0-9]+)
-
beego.Router(“/:hi:string”, &controllers.RController{})
string 類型設置方式盔粹,匹配 :hi 為 string 類型隘梨。框架幫你實現(xiàn)了正則 ([\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 規(guī)則
上面列舉的是默認的請求方法名(請求的 method 和函數(shù)名一致出嘹,例如 GET
請求執(zhí)行 Get
函數(shù)席楚,POST
請求執(zhí)行 Post
函數(shù))咬崔,如果用戶期望自定義函數(shù)名,那么可以使用如下方式:
beego.Router("/",&IndexController{},"*:Index")
使用第三個參數(shù)烦秩,第三個參數(shù)就是用來設置對應 method 到函數(shù)名垮斯,定義如下
-
*
表示任意的 method 都執(zhí)行該函數(shù) - 使用 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 指向同一個函數(shù)的示例:
beego.Router("/api",&RestController{},"get,post:ApiFunc")
以下是不同的 method 對應不同的函數(shù)只祠,通過 ; 進行分割的示例:
beego.Router("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
可用的 HTTP Method:
- *: 包含以下所有的函數(shù)
- get: GET 請求
- post: POST 請求
- put: PUT 請求
- delete: DELETE 請求
- patch: PATCH 請求
- options: OPTIONS 請求
- head: HEAD 請求
如果同時存在 * 和對應的 HTTP Method兜蠕,那么優(yōu)先執(zhí)行 HTTP Method 的方法,例如同時注冊了如下所示的路由:
beego.Router("/simple",&SimpleController{},"*:AllFunc;post:PostFunc")
那么執(zhí)行 POST
請求的時候抛寝,執(zhí)行 PostFunc
而不執(zhí)行 AllFunc
熊杨。
自定義函數(shù)的路由默認不支持 RESTful 的方法,也就是如果你設置了
beego.Router("/api",&RestController{},"post:ApiFunc")
這樣的路由盗舰,如果請求的方法是POST
晶府,那么不會默認去執(zhí)行Post
函數(shù)。
自動匹配
用戶首先需要把需要路由的控制器注冊到自動路由中:
beego.AutoRouter(&controllers.ObjectController{})
那么 beego 就會通過反射獲取該結構體中所有的實現(xiàn)方法钻趋,你就可以通過如下的方式訪問到對應的方法中:
/object/login 調用 ObjectController 中的 Login 方法
/object/logout 調用 ObjectController 中的 Logout 方法
除了前綴兩個 /:controller/:method
的匹配之外川陆,剩下的 url beego 會幫你自動化解析為參數(shù),保存在 this.Ctx.Input.Params
當中:
/object/blog/2013/09/12 調用 ObjectController 中的 Blog 方法蛮位,參數(shù)如下:map[0:2013 1:09 2:12]
方法名在內部是保存了用戶設置的较沪,例如 Login,url 匹配的時候都會轉化為小寫失仁,所以尸曼,/object/LOGIN
這樣的 url
也一樣可以路由到用戶定義的 Login
方法中。
現(xiàn)在已經可以通過自動識別出來下面類似的所有 url萄焦,都會把請求分發(fā)到 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 函數(shù)注冊是一樣的:
beego.Router("/staticblock/:key", &CMSController{}, "get:StaticBlock")
beego.Router("/all/:key", &CMSController{}, "get:AllBlock")
同時大家注意到新版本里面增加了 URLMapping 這個函數(shù)镣衡,這是新增加的函數(shù)霜定,用戶如果沒有進行注冊档悠,那么就會通過反射來執(zhí)行對應的函數(shù),如果注冊了就會通過 interface 來進行執(zhí)行函數(shù)望浩,性能上面會提升很多辖所。
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 對象,下面這些函數(shù)都是 namespace 對象的方法,但是強烈推薦使用 NS 開頭的相應函數(shù)注冊缘回,因為這樣更容易通過 gofmt 工具看的更清楚路由的級別關系
-
NSCond(cond namespaceCond)
支持滿足條件的就執(zhí)行該 namespace, 不滿足就不執(zhí)行
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)
上面這些都是設置路由的函數(shù),詳細的使用和上面 beego 的對應函數(shù)是一樣的
-
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")) }), ), )
下面這些函數(shù)都是屬于 *Namespace 對象的方法:不建議直接使用典挑,當然效果和上面的 NS 開頭的函數(shù)是一樣的酥宴,只是上面的方式更優(yōu)雅,寫出來的代碼更容易看得懂
-
Cond(cond namespaceCond)
支持滿足條件的就執(zhí)行該 namespace, 不滿足就不執(zhí)行,例如你可以根據域名來控制 namespace
-
Filter(action string, filter FilterFunc)
action 表示你需要執(zhí)行的位置, before 和 after 分別表示執(zhí)行邏輯之前和執(zhí)行邏輯之后的 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)
上面這些都是設置路由的函數(shù),詳細的使用和上面 beego 的對應函數(shù)是一樣的
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(創(chuàng)建)您觉、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)