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

第49章 Iris 框架中的 JSON 响应处理

JSON 响应

了解如何在 Iris 中发送 JSON 响应。

基础 JSON 响应

```go package main import "github.com/kataras/iris/v12" type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } func main() { app := iris.New() app.Get("/json", func(ctx iris.Context) { user := User{ ID: 1, Name: "John Doe", Email: "john@example.com", } ctx.JSON(user) }) app.Listen(":8080") } ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

美化 JSON

```go app.Get("/pretty", func(ctx iris.Context) { data := iris.Map{ "message": "Hello", "status": "success", "data": iris.Map{ "name": "John", "age": 25, }, } ctx.JSON(data, iris.JSON{ Indent: " ", }) }) ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14

自定义 JSON 编码

```go app.Get("/custom", func(ctx iris.Context) { type CustomTime time.Time type Event struct { ID int `json:"id"` Name string `json:"name"` Timestamp CustomTime `json:"timestamp"` } event := Event{ ID: 1, Name: "Meeting", Timestamp: CustomTime(time.Now()), } ctx.JSON(event, iris.JSON{ UnescapeHTML: true, StreamingJSON: true, }) }) ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

最佳实践

结构

- 使用正确的 Tag - 遵循命名规范 - 记录 Schema - 处理类型 - 验证输出

性能

- 启用压缩 - 使用流式传输 - 缓存响应 - 监控数据大小 - 处理超时

安全性

- 验证输入 - 转义输出 - 设置 Header - 处理错误 - 监控使用情况

维护

- 记录 Schema - 更新结构 - 监控变更 - 定期测试 - 审查安全

评论 (0)