SSE Routes
Overview
Section titled “Overview”go-zero now supports Server-Sent Events (SSE) through the sse: true annotation in the @server directive. This enables real-time event streaming from the server to clients.
SSE Support
Section titled “SSE Support”syntax = "v1"
type EventMessage { Type string `json:"type"` Data string `json:"data"`}
@server ( sse: true prefix: /api/v1)service EventApi { @handler StreamEvents get /events returns (EventMessage)}Generated Code
Section titled “Generated Code”When sse: true is specified, goctl generates routes with the rest.WithSSE() option:
server.AddRoutes( []rest.Route{ { Method: http.MethodGet, Path: "/events", Handler: StreamEventsHandler(serverCtx), }, }, rest.WithPrefix("/api/v1"), rest.WithSSE(),)Implementation Details
Section titled “Implementation Details”The rest.WithSSE() option automatically:
- Sets proper SSE headers (
Content-Type: text/event-stream,Cache-Control: no-cache, etc.) - Removes write timeouts to allow long-running connections
- Enables connection keep-alive
- SSE routes should typically use
GETmethod - The connection will remain open until the client disconnects or the handler completes
- SSE works well with JWT authentication and middleware