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

第56章 Iris 中实现 Server-Sent Events (SSE) 指南

Server-Sent Events (SSE) ​学习如何在 Iris 中实现 Server-Sent Events。 基础 SSE 实现 ​go(代码同上) ```go package main import ( "time" "github.com/kataras/iris/v12" ) func main() { app := iris.New() app.Get("/events", func(ctx iris.Context) { ctx.ContentType("text/event-stream") ctx.Header("Cache-Control", "no-cache") ctx.Header("Connection", "keep-alive") // 每秒发送一次事件 ctx.StreamWriter(func(w *bufio.Writer) bool { msg := fmt.Sprintf("data: {\"time\": \"%v\"}\n\n", time.Now().Unix()) w.WriteString(msg) w.Flush() time.Sleep(time.Second) return true }) }) app.Listen(":8080") } ``` 自定义事件类型 ​go: ```go app.Get("/custom-events", func(ctx iris.Context) { ctx.ContentType("text/event-stream") ctx.Header("Cache-Control", "no-cache") ctx.Header("Connection", "keep-alive") ctx.StreamWriter(func(w *bufio.Writer) bool { // 发送不同类型的事件 events := []struct { Type string Data string ID string Retry int }{ { Type: "user", Data: `{"name": "John"}`, ID: "1", }, { Type: "notification", Data: `{"message": "New message"}`, ID: "2", }, } for _, event := range events { if event.Type != "" { w.WriteString(fmt.Sprintf("event: %s\n", event.Type)) } if event.ID != "" { w.WriteString(fmt.Sprintf("id: %s\n", event.ID)) } if event.Retry > 0 { w.WriteString(fmt.Sprintf("retry: %d\n", event.Retry)) } w.WriteString(fmt.Sprintf("data: %s\n\n", event.Data)) w.Flush() time.Sleep(time.Second) } return true }) }) ``` 错误处理 ​goapp.Get("/events-with-error", func(ctx iris.Context) { ctx.ContentType("text/event-stream") ctx.Header("Cache-Control", "no-cache") ctx.Header("Connection", "keep-alive") ctx.StreamWriter(func(w *bufio.Writer) bool { select { case <-ctx.Request().Context().Done(): // 客户端已断开 return false case err := <-getErrorChannel(): // 处理错误 w.WriteString(fmt.Sprintf("event: error\ndata: %v\n\n", err)) w.Flush() return false default: // 发送常规事件 w.WriteString(fmt.Sprintf("data: {\"time\": \"%v\"}\n\n", time.Now().Unix())) w.Flush() time.Sleep(time.Second) return true } }) })1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
最佳实践 ​实现方面:正确设置请求头、处理断连、监控连接、清理资源及处理错误。性能方面:合理缓冲、监控内存、处理反压、优化事件及定期清理。安全方面:校验客户端、监控用量、处理超时、限制频率及控制访问。维护方面:监控连接、处理重连、定期测试、记录用法及审查性能。

评论 (0)