beego的URL構(gòu)建

2023-11-20 18:06 更新

如果可以匹配 URL ,那么 beego 也可以生成 URL 嗎?當(dāng)然可以。 UrlFor() 函數(shù)就是用于構(gòu)建指定函數(shù)的 URL 的。它把對(duì)應(yīng)控制器和函數(shù)名結(jié)合的字符串作為第一個(gè)參數(shù),其余參數(shù)對(duì)應(yīng) URL 中的變量。未知變量將添加到 URL 中作為查詢參數(shù)。 例如:

下面定義了一個(gè)相應(yīng)的控制器

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")))
}

下面是我們注冊(cè)的路由:

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

那么通過方式可以獲取相應(yīng)的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

模板中如何使用

默認(rèn)情況下,beego 已經(jīng)注冊(cè)了 urlfor 函數(shù),用戶可以通過如下的代碼進(jìn)行調(diào)用

{{urlfor "TestController.List"}}

為什么不在把 URL 寫死在模板中,反而要?jiǎng)討B(tài)構(gòu)建?有兩個(gè)很好的理由:

  1. 反向解析通常比硬編碼 URL 更直觀。同時(shí),更重要的是你可以只在一個(gè)地方改變 URL ,而不用到處亂找。
  2. URL 創(chuàng)建會(huì)為你處理特殊字符的轉(zhuǎn)義和 Unicode 數(shù)據(jù),不用你操心。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)