路由和反向查找

处理程序章节中,Iris 提供了些处理程序注册方式,每一种都返回一个 RouteNameFunc 类型。

路由命名

路由命名很简单,因为我们仅调用返回的 `RouteNameFunc`,使用一个字符串参数作为它的名称即可:

package main

import (
    "github.com/kataras/iris"
)

func main() {

    // define a function
    render := func(ctx *iris.Context) {
        ctx.Render("index.html", nil)
    }

    // handler registration and naming
    iris.Get("/", render)("home")
    iris.Get("/about", render)("about")
    iris.Get("/page/:id", render)("page")

    iris.Listen(":8080")
}

从路由名中生成url的路由

当我们为特定路径注册处理程序时,我们能够根据传递给 Iris 的结构化数据创建url。在上面的示例中,我们命名了三个路由器,其中一个甚至接受参数(第三个)。如果我们使用默认的 `html/template` 模板 引擎,我们可以使用一个简单的操作来反转路由(以及一般的url):

Home: {{ url "home" }}
About: {{ url "about" }}
Page 17: {{ url "page" "17" }}

上面的代码将生成下面的输出:

Home: http://0.0.0.0:8080/ 
About: http://0.0.0.0:8080/about
Page 17: http://0.0.0.0:8080/page/17

在代码中使用路由名称

我们可以使用以下方法/函数来使用已命名的路由(及其参数):

示例

点这里(原文链接有误,译者已更正)

results matching ""

    No results matching ""