Beego设置路由的文件位于routers目录下的 router.go 文件
实现路由的方式有一下几种
简单路由
beego.Get("hello1", func(context *context.Context) {
context.WriteString("Hello Beego\n")
})
这种路由不需要走controller,直接执行这个函数返回了Hello Beego。如果方法为Post,只需要把前面改成beego.Post即可
固定路由
最简单的设置路径到达controller
beego.Router("/hello",&controllers.HelloControllers{})
正则路由
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")获取变量
自定义路由
beego.Router("/rest",&controllers.CustomController{},"Get:GetFunc")
这代表使用Get方法将在CustomerController中调用GetFunc函数
自动匹配
beego.AutoRouter(&controllers.AutoController{})
如果请求http://localhost:8080/Auto/GetFunc/123/456这种api时会自动将第一个Auto当做controller,GetFunc当做函数,后面的为参数
注解路由
beego.Include(&controllers.HelloController{})
为HelloController注册注解路由,然后在这个controller中
// @router /staticblock/:key [get]
func (this *CMSController) StaticBlock() {
}