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

第35章 URL 查询参数

URL 查询参数 学习如何在 Iris 中处理 URL 查询参数。

基本查询参数 ```go package main

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

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

// GET /search?q=example&page=1 app.Get("/search", func(ctx iris.Context) { query := ctx.URLParam("q") page := ctx.URLParamIntDefault("page", 1)

ctx.JSON(iris.Map{ "query": query, "page": page, }) })

app.Listen(":8080") } ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

多个值 ```go app.Get("/tags", func(ctx iris.Context) { // GET /tags?tag=go&tag=web&tag=iris tags := ctx.URLParamSlice("tag")

ctx.JSON(iris.Map{ "tags": tags, }) }) ``` 1 2 3 4 5 6 7

类型转换 ```go app.Get("/filters", func(ctx iris.Context) { // String parameter name := ctx.URLParam("name")

// Integer parameter with default page := ctx.URLParamIntDefault("page", 1)

// Float parameter price := ctx.URLParamFloat64Default("price", 0.0)

// Boolean parameter active := ctx.URLParamBool("active")

ctx.JSON(iris.Map{ "name": name, "page": page, "price": price, "active": active, }) }) ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

必填参数 ```go app.Get("/required", func(ctx iris.Context) { id := ctx.URLParam("id") if id == "" { ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem(). Title("Validation Error"). Detail("ID parameter is required")) return }

ctx.JSON(iris.Map{ "id": id, }) }) ``` 1 2 3 4 5 6 7 8 9 10 11 12 13

最佳实践

验证 - 验证必填参数 - 检查参数类型 - 设置默认值 - 处理缺失值 - 净化输入

安全 - 验证参数长度 - 检查参数格式 - 防止注入 - 转义特殊字符 - 记录可疑输入

性能 - 缓存解析后的值 - 使用合适的类型 - 处理大型查询 - 监控查询大小 - 优化解析

错误处理 - 提供清晰的错误消息 - 处理无效类型 - 记录验证错误 - 返回正确的状态码 - 记录参数要求

评论 (0)