|
| 1 | +--- |
| 2 | +title: "SSE" |
| 3 | +date: 2025-05-21 |
| 4 | +weight: 12 |
| 5 | +keywords: ["SSE"] |
| 6 | +description: "Hertz Support SSE。" |
| 7 | +--- |
| 8 | +```Code:https://github.com/cloudwego/hertz/tree/develop/pkg/protocol/sse``` |
| 9 | + |
| 10 | +**Changelog** |
| 11 | +- 2025/05/15 Has been released to the open-source version v0.10.0 |
| 12 | +- 2025/05/13 [d3c68463] Added Get / SetLastEventID. |
| 13 | +- 2025/05/13 [3952e956] The Reader ForEach interface supports passing in ctx. |
| 14 | +- 2025/04/24 [cf38573ce] First version completed |
| 15 | + |
| 16 | +## 什么是Server-Sent Events (SSE) |
| 17 | +- SSE is an HTML standard used to describe the implementation of the EventSource API in browsers. Strictly speaking, it is not an HTTP protocol. |
| 18 | +- Both the popular Model Context Protocol (MCP) and Agent2Agent (A2A) protocols are based to some extent on SSE |
| 19 | + - https://www.anthropic.com/news/model-context-protocol |
| 20 | + - https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/ |
| 21 | + |
| 22 | +## Server Implementation |
| 23 | +### Return data |
| 24 | +```go |
| 25 | +import "github.com/cloudwego/hertz/pkg/protocol/sse" |
| 26 | + |
| 27 | +func HandleSSE(ctx context.Context, c *app.RequestContext) { |
| 28 | + println("Server Got LastEventID", sse.GetLastEventID(&c.Request)) |
| 29 | + w := sse.NewWriter(c) |
| 30 | + for i := 0; i < 5; i++ { |
| 31 | + w.WriteEvent("id-x", "message", []byte("hello\n\nworld")) |
| 32 | + time.Sleep(10 * time.Millisecond) |
| 33 | + } |
| 34 | + w.Close() // 发送最后的chunk数据,确保优雅退出。可选,Hertz 在 Handler 返回后会自动调用。 |
| 35 | + |
| 36 | + // 请确保 writer 的生命周期和handler一致。不要go异步后台使用。 |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | + |
| 41 | +### FAQ |
| 42 | +#### connection has been closed when flush |
| 43 | +Reason: The client connection has been disconnected, possibly due to a long time without response data. Please check the corresponding configuration. |
| 44 | + |
| 45 | + |
| 46 | +## Client Implementation |
| 47 | + |
| 48 | +### Initiate a request |
| 49 | +It's exactly the same as making a normal HTTP request to Hertz. |
| 50 | +Note: The new Hertz version will automatically recognize SSE streams, so you don't need to explicitly set `WithResponseBodyStream(true)` |
| 51 | + |
| 52 | +**Some optional headers** |
| 53 | +```go |
| 54 | +import "github.com/cloudwego/hertz/pkg/protocol/sse" |
| 55 | + |
| 56 | +sse.AddAcceptMIME(req) // 部分SSE Server可能会要求显式增加 Accept: text/event-stream |
| 57 | +sse.SetLastEventID(req, "id-123") // 对于有状态服务,需要通过 SetLastEventID 告诉 Server |
| 58 | +``` |
| 59 | + |
| 60 | +### Handle response |
| 61 | +```go |
| 62 | +import "github.com/cloudwego/hertz/pkg/protocol/sse" |
| 63 | + |
| 64 | +func HandleSSE(ctx context.Context, resp *protocol.Response) error { |
| 65 | + r, err := sse.NewReader(resp) |
| 66 | + if err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + |
| 70 | + // 也可以手动调用 r.Read 方法 |
| 71 | + err = r.ForEach(ctx, func(e *Event) error { |
| 72 | + println("Event:", e.String()) |
| 73 | + return nil |
| 74 | + }) |
| 75 | + if err != nil { // 如果 Server 正常断开,这里 err == nil,不会报错 |
| 76 | + // 其他io错误 或 ctx cancelled |
| 77 | + return err |
| 78 | + } |
| 79 | + println("Client LastEventID", r.LastEventID()) // 可用于保存最后接收的 Event ID |
| 80 | + return nil |
| 81 | +} |
| 82 | +``` |
| 83 | + |
| 84 | +### FAQ |
| 85 | + |
| 86 | +#### How to implement multi-level SSE/SSE Proxy? |
| 87 | +- You can refer to the implementations on both the Client and Server sides simultaneously |
| 88 | +- Enable `WithSenseClientDisconnection` in the server and pass the context to the next hop's Reader ForEach |
| 89 | + - In this way, when the Client disconnects, it will be automatically recognized, and the entire stream will be interrupted |
| 90 | + |
| 91 | +## Event Struct |
| 92 | +```go |
| 93 | +// Event represents a Server-Sent Event (SSE). |
| 94 | +type Event struct { |
| 95 | + ID string // 即 Event ID,sse.Reader 会自动记录最后的 Event ID,可使用 LastEventID() 获取 |
| 96 | + Type string // 即 Event Type,常见的如 "message" |
| 97 | + Data []byte // 为了方便使用 Unmarshal/Marshal,这里使用 []byte,但是按spec这个字段必须要 utf8 string |
| 98 | + |
| 99 | + // 不建议使用,主要是针对浏览器的 SourceEvent 返回该字段控制其重试策略。 |
| 100 | + // 如果使用Hertz作为Client可以参考:https://www.cloudwego.io/docs/hertz/tutorials/basic-feature/retry/ |
| 101 | + Retry time.Duration |
| 102 | +} |
| 103 | +``` |
0 commit comments