Beego --- 路由

0. 基本使用

func init() {
    // 如果有指定参数,必须指定对应方法才会匹配对应方法处理,否则访问不到,
    // 例如:如果不写post 则访问不到POST方法,以分号分割
    beego.Router("/", &controllers.MainController{},"get:方法名;post:方法名")  // 指定get请求 匹配对应的方法
}

1. 正则路由匹配规则

beego.Router("/api/?:id", &controllers.RController{})
默认匹配 //例如对于URL"/api/123"可以匹配成功,此时变量":id"值为"123"
Controller 获取变量的值:this.Ctx.Input.Param(":id")

beego.Router("/api/:id", &controllers.RController{})
默认匹配 //例如对于URL"/api/123"可以匹配成功,此时变量":id"值为"123",但URL"/api/"匹配失败
Controller 获取变量的值: this.Ctx.Input.Param(":id")

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"
Controller 获取变量的值: this.Ctx.Input.Param(":username")


beego.Router("/download/*.*", &controllers.RController{})
*匹配方式 //例如对于URL"/download/file/api.xml"可以匹配成功,此时变量":path"值为"file/api", ":ext"值为"xml"
Controller 获取变量的值: this.Ctx.Input.Param(":path")


beego.Router("/download/ceshi/*", &controllers.RController{})
*全匹配方式 //例如对于URL"/download/ceshi/file/api.json"可以匹配成功,此时变量":splat"值为"file/api.json"
Controller 获取变量的值: this.Ctx.Input.Param(":splat")
this.Ctx.Input.Param(":ext")


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

2. 路由绑定自定义方法及 RESTful 规则

beego.Router("/",&IndexController{},"*:Index")  # 表示这个请求执行index函数

*表示任意的 method 都执行该函数
使用 httpmethod:funcname 格式来展示
多个不同的格式使用 ; 分割
多个 method 对应同一个 funcname,method 之间通过 , 来分割

示例

  1. 以下是一个 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")
  1. 多个 HTTP Method 指向同一个函数的示例:
beego.Router("/api",&RestController{},"get,post:ApiFunc")
  1. 不同的 method 对应不同的函数,通过 ; 进行分割的示例:
beego.Router("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
  1. 如果同时存在 * 和对应的 HTTP Method,那么优先执行 HTTP Method 的方法,例如同时注册了如下所示的路由:
beego.Router("/simple",&SimpleController{},"`*:AllFunc;post:PostFunc`")

# 那么执行 POST 请求的时候,执行 PostFunc 而不执行 AllFunc。
# 以上路由定义方式,如果你设置了 beego.Router("/api",&RestController{},"post:ApiFunc") 这样的路由,
# 如果请求的方法是 POST,那么不会默认去执行 Post 函数,而是ApiFunc 函数

3. 动匹配

  1. 首先把路由的控制器注册到自动路由中:
beego.AutoRouter(&controllers.ObjectController{})
  1. 那么 beego 就会通过反射获取该结构体中所有的实现方法,你就可以通过如下的方式访问到对应的方法中:
/object/login   调用 ObjectController 中的 Login 方法
/object/logout  调用 ObjectController 中的 Logout 方法
  1. 除了前缀两个 /:controller/:method 的匹配之外,剩下的 url beego 会帮你自动化解析为参数,
    保存在 this.Ctx.Input.Params 当中:
/object/blog/2013/09/12  调用 ObjectController 中的 Blog 方法,参数如下:map[0:2013 1:09 2:12]
  1. 方法名在内部是保存了用户设置的,例如 Login,url 匹配的时候都会转化为小写,
    所以,/object/LOGIN 这样的 url 也一样可以路由到用户定义的 Login 方法中。
  2. 现在已经可以通过自动识别出来下面类似的所有 url,都会把请求分发到 controller 的 simple 方法:
/controller/simple
/controller/simple.html
/controller/simple.json
/controller/simple.xml

# 可以通过 this.Ctx.Input.Param(":ext") 获取后缀名。

4. 注解路由

从 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 来进行执行函数,性能上面会提升很多。

5. 命名空间

//初始化 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

  1. GET /v1/notallowed
  2. GET /v1/version
  3. GET /v1/changepassword
  4. POST /v1/changepassword
  5. GET /v1/shop/123
  6. 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)

6. URL 反向解析

如果可以匹配 URL ,那么 beego 也可以生成 URL 吗?当然可以。 UrlFor() 函数就是用于构建指定函数的 URL 的。它把对应控制器和函数名结合的字符串作为第一个参数,
其余参数对应 URL 中的变量。未知变量将添加到 URL 中作为查询参数。 例如:
下面定义了一个相应的控制器

type TestController struct {
    beego.Controller
}

func (this *TestController) Get() {
    this.Data["Username"] = "astaxie"
    this.Ctx.Output.Body([]byte("ok"))
}

func (this *TestController) List() {
    this.Ctx.Output.Body([]byte("i am list"))
}

func (this *TestController) Params() {
    this.Ctx.Output.Body([]byte(this.Ctx.Input.Params()["0"] + this.Ctx.Input.Params()["1"] + this.Ctx.Input.Params()["2"]))
}

func (this *TestController) Myext() {
    this.Ctx.Output.Body([]byte(this.Ctx.Input.Param(":ext")))
}

func (this *TestController) GetUrl() {
    this.Ctx.Output.Body([]byte(this.UrlFor(".Myext")))
}

下面是我们注册的路由:

beego.Router("/api/list", &TestController{}, "*:List")
beego.Router("/person/:last/:first", &TestController{})
beego.AutoRouter(&TestController{})

那么通过方式可以获取相应的URL地址:

beego.URLFor("TestController.List")
// 输出 /api/list

beego.URLFor("TestController.Get", ":last", "xie", ":first", "asta")
// 输出 /person/xie/asta

beego.URLFor("TestController.Myext")
// 输出 /Test/Myext

beego.URLFor("TestController.GetUrl")
// 输出 /Test/GetUrl

2. 模板中使用

默认情况下,beego 已经注册了 urlfor 函数,用户可以通过如下的代码进行调用

{{urlfor "TestController.List"}}

什么不在把 URL 写死在模板中,反而要动态构建?有两个很好的理由:

  1. 反向解析通常比硬编码 URL 更直观。同时,更重要的是你可以只在一个地方改变 URL ,而不用到处乱找。
  2. URL 创建会为你处理特殊字符的转义和 Unicode 数据,不用你操心
posted @ 2024-09-19 17:12  河图s  阅读(134)  评论(0)    收藏  举报