begoo——路由设置
路由本质是URL与要为该URL调用的视图函数之间的映射表,其实就是你定义的使用那个URL调用那段代码的关系对应表。
首先看一下最简单的路由:
1 2 3 4 5 6 7 8 9 10 | package routers import ( "pro1/controllers" "github.com/astaxie/beego" ) func init() { <strong>beego.Router( "/" , &controllers.MainController{})</strong> } |
以及对应的控制器函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package controllers import ( "github.com/astaxie/beego" ) type MainController struct { beego.Controller } func (c *MainController) <strong>Get()</strong> { c.Data[ "Website" ] = "beego.me" c.Data[ "Email" ] = "astaxie@gmail.com" c.TplName = "index.tpl" } |
基础路由
从beego1.2版本开始支持基本的RESTful函数式路由,应用中大多数路由都会定义在routers/router.go文件中。
基本GET路由
1 2 3 | beego.Get( "/" , func (ctx *context.Context){ ctx.Output.Body([]byte( "hello world" )) }) |
基本POST路由
1 2 3 | beego.Post( "/alice" , func (ctx *context.Context){ ctx.Output.Body([]byte( "bob" )) }) |
注册一个可以响应任何HTTP的路由
1 2 3 | 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中来,现在可以很方便的集成。
1 2 3 4 | 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这样的也会匹配去运行。
固定路由
固定路由也就是全匹配的路由,如下所示:
1 2 3 4 | 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中通过如下方式获取上面的变量。
1 2 3 4 5 | 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函数),如果用户期望自定义函数名,那么可以使用如下方式:
1 | beego.Router( "/" ,&IndexController{}, "*:Index" ) |
使用第三个参数,第三个参数就是用来设置对应method到函数名,定义如下:
- *表示任意的method都执行该函数
- 使用httpmethod:funcname格式来显式
- 多个不同的格式使用;分割
- 多个method对应同一个funcname,method之间通过“,”来分割
以下是一个RESTful的设计示例:
1 2 3 4 | 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指向同一个函数的示例:
1 | beego.Router( "/api" ,&RestController{}, "get,post:ApiFunc" ) |
以下是不同的method对应不同的函数,通过“;”进行分割的示例:
1 | 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方法,例如同时注册了如下所示的路由:
1 | beego.Router( "/simple" ,&SimpleController{}, "*:AllFunc;post:PostFunc" ) |
那么执行Post请求的时候,执行PostFunc而不执行AllFunc。
自定义函数的路由默认不支持RESTful方法,也就是如果你设置了beego.Router("/api",&RestController{},"post:ApiFunc")这样的路由,如果请求的方法是POST,那么不会默认去执行Post函数。
自动匹配
用户首先需要把需要路由的控制器注册到自动路由中:
1 | beego.<strong>AutoRouter</strong>(&controllers.ObjectController{}) |
那么beego就会通过反射获取该结构体中所有的实现方法,你可以通过如下方式访问到对应的方法中:
1 2 | /object/<strong>login</strong> <strong>调用 ObjectController 中的 Login 方法</strong> /object/<strong>logout</strong> <strong>调用 ObjectController 中的 Logout 方法</strong> |
除了前缀两个 /:controller/:method
的匹配之外,剩下的 url beego 会帮你自动化解析为参数,保存在 this.Ctx.Input.Params
当中:
1 | /object/blog/2013/09/12 调用 ObjectController 中的 Blog 方法,参数如下: map [0:2013 1:09 2:12] |
方法名在内部是保存了用户设置的,例如 Login,url 匹配的时候都会转化为小写,所以,/object/LOGIN
这样的 url
也一样可以路由到用户定义的 Login
方法中。
现在已经可以通过自动识别出来下面类似的所有 url,都会把请求分发到 controller
的 simple
方法:
1 2 3 4 | /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)就可以了,详细的使用请看下面的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // 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中通过如下方式注册路由:
1 | beego.Include(&CMSController{}) |
beego自动会进行源码分析,注意只会在dev模式下进行生成,生成的路由放在“/routers/commentsRouter.go” 文件中。
这样上面的路由就支持了如下的路由:
- GET /staticblock/:key
- GET /all/:key
其实效果和自己通过 Router 函数注册是一样的:
1 2 | beego.Router( "/staticblock/:key" , &CMSController{}, "get:StaticBlock" ) beego.Router( "/all/:key" , &CMSController{}, "get:AllBlock" ) |
同时大家注意到新版本里面增加了 URLMapping 这个函数,这是新增加的函数,用户如果没有进行注册,那么就会通过反射来执行对应的函数,
如果注册了就会通过 interface 来进行执行函数,性能上面会提升很多。
namespace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | //初始化 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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)
更多的例子代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | //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) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2017-12-14 MySQL——并发控制(锁)
2017-12-14 MySQL——多版本并发控制
2017-12-14 MySQL——事务
2017-12-14 Redis的特性
2017-12-14 Docker与虚拟化