Server-Sent Events(SSE)
Description
This example demonstrates how to implement Server-Sent Events (SSE) using GoFrame. Server-Sent Events is a technology that allows a server to push updates to a client via HTTP connection. Unlike WebSocket, SSE is unidirectional - only the server can send data to the client.
The example implements a simple SSE server that streams responses character by character, simulating a real-time typing effect commonly seen in modern AI chat applications.
Requirements
Structure
- go.mod: The Go module file.
- main.go: The main application entry point with SSE implementation.Features
- Server-Sent Events implementation
- Character-by-character streaming response for simulated AI chat
- Proper HTTP headers for SSE
Setup
Clone the repository:
git clone https://github.com/gogf/examples.git cd examples/httpserver/sseInstall the dependencies:
go mod tidyRun the application:
go run main.go
Usage
Run the example:
go run main.goThe server will start at: http://127.0.0.1:8000
Access the SSE endpoint:
- In a browser, navigate to: http://127.0.0.1:8000/ai/chat
- You should see words appearing one by one with a typing effect
Implementation Details
The SSE implementation includes:
Setting the correct HTTP headers for SSE:
Content-Type: text/event-streamCache-Control: no-cacheConnection: keep-alive
Streaming response with proper flushing
Simulated typing delay using
time.SleepSimple HTTP routing with GoFrame's router
Notes
SSEconnections remain open until explicitly closed by the client- The server must flush the response buffer after each message
- For production use, consider implementing reconnection logic and event IDs
SSEworks over regularHTTP/HTTPSand supports automatic reconnection in browsers