动态路由参数

未匹配的标注

动态路由参数

Iris 有你曾经遇到过的最简单,最强大的路由程序。

同时,对于路由的路径声明语法,动态路径参数解析和计算,Iris 有自己的解释器(就像一个编程语言)。我们简单的把他们叫做 「宏」.

到底如何呢?它计算了它的需求,如果不需要任何特殊的正则表达式,那么它只是用低级路径语法注册路由,否则它预先编译正则表达式并添加必要的中间件。这意味着与其他路由器或Web框架相比,您的性能成本为零。

路由路径参数标准 macro 类型。

+------------------------+
| {param:string}         |
+------------------------+
string type
anything

+------------------------+
| {param:int}            |
+------------------------+
int type
only numbers (0-9)

+------------------------+
| {param:long}           |
+------------------------+
int64 type
only numbers (0-9)

+------------------------+
| {param:boolean}        |
+------------------------+
bool type
only "1" or "t" or "T" or "TRUE" or "true" or "True"
or "0" or "f" or "F" or "FALSE" or "false" or "False"

+------------------------+
| {param:alphabetical}   |
+------------------------+
alphabetical/letter type
letters only (upper or lowercase)

+------------------------+
| {param:file}           |
+------------------------+
file type
letters (upper or lowercase)
numbers (0-9)
underscore (_)
dash (-)
point (.)
no spaces ! or other character

+------------------------+
| {param:path}           |
+------------------------+
path type
anything, should be the last part, more than one path segment,
i.e: /path1/path2/path3 , ctx.Params().Get("param") == "/path1/path2/path3"

如果没有设置参数类型,默认就是 string,所以  {param} == {param:string}

如果在该类型上找不到函数,那么 string 宏类型的函数将被使用。

除了 iris 提供的基本类型和一些默认的 「宏函数」,你也可以注册自己的。

注册一个命名的路径参数函数。

app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool {
    // [...]
    return true
        // true 意味着有效,false 意味着无效,将触发404错误,或者如果 「else 500」被添加到宏语法之后,将造成内部服务错误 500。
})
//上述写法有问题,应该如下操作(下文错误写法请参考这)-----iris version 11.2.0:
import "github.com/kataras/iris/macro"
    macro.Int.RegisterFunc("min", func(minValue int) func(string) bool {
        return  func(paramValue string) bool {
            n, err  := strconv.Atoi(paramValue)
            if err !=  nil {
                return  false
            }
            return n >= minValue
        }
    })

在  func(argument ...)  这里,你可以使用任何标准类型,它将在服务器启动之前进行验证,所以不用关心任何性能为题,在服务运行时,它唯一的事情是返回 func(paramValue string) bool

{param:string equal(iris)} , "iris" will be the argument here:
app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool {
    return func(paramValue string){ return argument == paramValue }
})

示例代码:

app := iris.New()
// 对于一个可以是任何类型的单个路径参数,你可以使用 「string」类型。
app.Get("/username/{name}", func(ctx iris.Context) {
    ctx.Writef("Hello %s", ctx.Params().Get("name"))
}) // 省略类型 = {name:string}

// 让我们注册我们第一个添加到 int 类型的宏函数
// "min" = 函数名称
// "minValue" = 函数参数
// func(string) bool = 宏的路径参数的求值函数,当用户请求包含 min(...) 
// 宏的 :int 路径参数的 URL 时,这个函数将会执行
app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool {
    return func(paramValue string) bool {
        n, err := strconv.Atoi(paramValue)
        if err != nil {
            return false
        }
        return n >= minValue
    }
})

// http://localhost:8080/profile/id>=1
// 如果路由是这样:/profile/0, /profile/blabla, /profile/-1,将抛出404错误
// 宏参数函数是可以省略的。
app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) {
        // 第二个参数是错误的,但是它将是 nil,因为我们用了宏
    // 验证已经执行了。
    id, _ := ctx.Params().GetInt("id")
    ctx.Writef("Hello id: %d", id)
})

// 改变路径参数错误引起的错误码:
app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx iris.Context) {
    id, _ := ctx.Params().GetInt("id")
    friendid, _ := ctx.Params().GetInt("friendid")
    ctx.Writef("Hello id: %d looking for friend id: ", id, friendid)
}) 
// 这将抛出 504 错误码,而不是404,如果所有的路由宏没通过。

// http://localhost:8080/game/a-zA-Z/level/0-9
// 记着,alphabetical 仅仅允许大小写字母。
app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx iris.Context) {
    ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level"))
})

// 让我们用一个简单的自定义正则表达式来验证一个路径参数仅仅是小写字母

// http://localhost:8080/lowercase/anylowercase
app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx iris.Context) {
    ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
})

// http://localhost:8080/single_file/app.js
app.Get("/single_file/{myfile:file}", func(ctx iris.Context) {
    ctx.Writef("file type validates if the parameter value has a form of a file name, got: %s", ctx.Params().Get("myfile"))
})

// http://localhost:8080/myfiles/any/directory/here/
// 这是唯一一个接受任何数量路径片段的宏类型。
app.Get("/myfiles/{directory:path}", func(ctx iris.Context) {
    ctx.Writef("path type accepts any number of path segments, path after /myfiles/ is: %s", ctx.Params().Get("directory"))
})

app.Run(iris.Addr(":8080"))
}

一个路径参数名称应该只包含小写字母,像 _ 和数字这样的符号是 允许的。

最后,不要困惑  ctx.Params()ctx.Values()。路径参数值获取通过 ctx.Params(),上下文中用于处理器之间通信的局部存储和中间件使用 ctx.Values()

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/iris-go/10/rout...

译文地址:https://learnku.com/docs/iris-go/10/rout...

上一篇 下一篇
贡献者:1