进阶 www.iris-go.com 2026-10-20 02:39:14 · 17 阅读

第34章 Iris 框架 URL 路径参数详解

第34章 URL 路径参数

学习如何在 Iris 框架中处理 URL 路径参数。

基本路径参数

```golang package main

import "github.com/kataras/iris/v12"

func main() { app := iris.New()

// GET /users/42 app.Get("/users/{id}", func(ctx iris.Context) { id := ctx.Params().Get("id") ctx.JSON(iris.Map{ "id": id, }) })

app.Listen(":8080") } ```

多个参数

```golang app.Get("/users/{userID}/posts/{postID}", func(ctx iris.Context) { userID := ctx.Params().Get("userID") postID := ctx.Params().Get("postID")

ctx.JSON(iris.Map{ "userID": userID, "postID": postID, }) }) ```

参数类型

```golang // 整型参数 app.Get("/users/{id:int}", func(ctx iris.Context) { id := ctx.Params().GetIntDefault("id", 0) ctx.JSON(iris.Map{ "id": id, }) })

// 字符串参数(仅限字母) app.Get("/categories/{name:string}", func(ctx iris.Context) { name := ctx.Params().Get("name") ctx.JSON(iris.Map{ "name": name, }) })

// UUID 参数 app.Get("/resources/{id:uuid}", func(ctx iris.Context) { id := ctx.Params().Get("id") ctx.JSON(iris.Map{ "id": id, }) }) ```

可选参数

```golang app.Get("/files/{directory:string}/{name:string}", func(ctx iris.Context) { directory := ctx.Params().GetStringDefault("directory", "default") name := ctx.Params().Get("name")

ctx.JSON(iris.Map{ "directory": directory, "name": name, }) }) ```

通配符参数

```golang app.Get("/assets/{path:path}", func(ctx iris.Context) { path := ctx.Params().Get("path") ctx.JSON(iris.Map{ "path": path, }) }) ```

最佳实践

参数类型:使用合适的类型,验证输入,处理转换,设置默认值,并记录需求 安全性:验证参数,防止注入,转义值,检查长度,监控使用情况 性能:缓存解析后的值,优化路由,处理长路径,监控性能,清理资源 实现:使用描述性名称,处理缺失值,记录模式,测试边界情况,遵循惯例

评论 (0)