iris 动态路由参数

iris 拥有最简单、最强大的路由处理能力。Iris 有自己的路由解释器,可以解析路径声明语法、动态路径参数以及进行计算。

iris 路由语法解释器称为「宏」(Macros)。它不仅支持最基本的路由声明,而且支持正则表达式。

 

1. 简单的路由声明

package main
import "github.com/kataras/iris"

func main() {
    app := iris.New()
    
    // 获取路由参数name
    app.Get("/username/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        ctx.WriteString("name=" + name)
    })
    app.Run(iris.Addr(":8000")
}

运行程序,浏览器中输入地址:http://localhost:8000/username/codebaoku ,你就会看到浏览器输出 name=codebaoku。

 

2. 带参数类型的路由声明

package main
import "github.com/kataras/iris"

func main() {
    app := iris.New()
    
    // 获取路由参数id
    app.Get("/userid/{id:int}", func(ctx iris.Context) {
        id := ctx.Params().Get("id")
        ctx.WriteString("id=" + id)
    })
    app.Run(iris.Addr(":8000")
}

其中 {id:int} 声明了参数是整形,如果其它类型的参数,比如字符串就无法匹配。

运行程序,浏览器中输入地址:http://localhost:8000/userid/100 ,你就会看到浏览器输出 id=100。

如果输入 http://localhost:8000/userid/codebaoku,那么浏览器会输出 Not Found,因为 codebaoku 不是整数,无法匹配。

 

3. 带函数的路由声明

package main
import "github.com/kataras/iris"

func main() {
    app := iris.New()
    
    // 获取路由参数id
    app.Get("/userid/{id:int max(99)}", func(ctx iris.Context) {
        id := ctx.Params().Get("id")
        ctx.WriteString("id=" + id)
    })
    app.Run(iris.Addr(":8000")
}

其中 {id:int max(2)} 声明了参数是整形,而且最大值为 99。

运行程序,浏览器中输入地址:http://localhost:8000/userid/88 ,你就会看到浏览器输出 id=88。

如果输入 http://localhost:8000/userid/100,那么浏览器会输出 Not Found。因为 100 已超出设定的最大值 99,所以无法匹配。

 

4. 使用正则表达式的路由声明

package main
import "github.com/kataras/iris"

func main() {
    app := iris.New()
    
    // 获取路由参数name
    app.Get("/username/{name:regexp(^[a-z]+)}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        ctx.WriteString("name=" + name)
    })
    app.Run(iris.Addr(":8000")
}

其中 {name:regexp(^[a-z]+)} 声明了参数必须是小写字母,其中 ^[a-z]+) 是一个正则表达式。

运行程序,浏览器中输入地址:http://localhost:8000/username/codebaoku ,你就会看到浏览器输出 name=codebaoku

如果输入 http://localhost:8000/username/Codebaoku,那么浏览器会输出 Not Found。因为 Codebaoku 不全是小写字母,所以无法匹配。

 

5. 路由路径参数标准 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 宏类型的函数将被使用。

 

7. 路由路径参数标准 macro 类型

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

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

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

 

8. 完整的范例

package main
import "github.com/kataras/iris"

func main() {
    app := iris.New()
    
    // 使用基本路由参数
    app.Get("/username/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        fmt.Println(name)
    })
    
    // 使用函数路由参数
    app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) {
        i, e := ctx.Params().GetInt("id")
        if e != nil {
            ctx.WriteString("error you input")
        }
    
        ctx.WriteString(strconv.Itoa(i))
    })
    
    // 设置错误码
    app.Get("/profile/{id:int min(1)}/friends/{friendid:int max(8) else 504}", func(ctx iris.Context) {
        i, _ := ctx.Params().GetInt("id")
        getInt, _ := ctx.Params().GetInt("friendid")
        ctx.Writef("Hello id:%d looking for friend id: ",i,getInt)
    })// 如果没有传递所有路由的macros,这将抛出504错误代码而不是404.
    
    // 使用正则表达式
    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"))
    })
    
    app.Run(iris.Addr(":8000"))
}
 

iris 路由可以设置名称是比较简单的,因为我们只需要设置返回的 *Route 实例的 Name 字段即可。package mainimport ( "github.com/kataras/iris ...