第57章 Iris 框架中的流式响应实践
第57章 流式响应 了解如何在 Iris 中发送流式响应。
基础流式传输 go package main
import ( "time" "github.com/kataras/iris/v12" )
func main() { app := iris.New()
app.Get("/stream", func(ctx iris.Context) { ctx.ContentType("text/plain") for i := 0; i < 10; i++ { ctx.Writef("Message %d\n", i) ctx.ResponseWriter().Flush() time.Sleep(time.Second) } })
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
Stream Writer go app.Get("/writer", func(ctx iris.Context) { ctx.StreamWriter(func(w *bufio.Writer) bool { msg := fmt.Sprintf("Server time: %s\n", time.Now().Format(time.RFC3339)) w.WriteString(msg) w.Flush() time.Sleep(time.Second) return true // 继续流式传输 }) }) 1 2 3 4 5 6 7 8 9
JSON 流式传输 go app.Get("/json-stream", func(ctx iris.Context) { ctx.ContentType("application/json") enc := json.NewEncoder(ctx.ResponseWriter()) for i := 0; i < 10; i++ { data := iris.Map{ "message": fmt.Sprintf("Message %d", i), "time": time.Now(), } enc.Encode(data) ctx.ResponseWriter().Flush() time.Sleep(time.Second) } }) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
最佳实践 实现方面: 处理超时 监控连接 定期 Flush 处理错误 清理资源
性能方面: 合理设置缓冲 监控内存 处理背压(backpressure) 优化写入操作 定期清理
请求头方面: 设置 Content-Type 配置 chunked 传输 处理压缩 监控客户端 设置超时
维护方面: 监控流状态 处理断开连接 定期测试 编写使用文档 定期评估性能