Introduction to Server-Sent Events (SSE) with Go Server and JavaScript Client
Server-Sent Events (SSE) provide a lightweight, HTTP‑based one‑way real‑time communication method, ideal for scenarios like financial data, social feeds, and log monitoring; the article explains its principles, advantages, message format, compares it with WebSockets, and offers complete Go server and JavaScript client code examples with deployment tips.
Introduction
In modern web development, real‑time data push is a core requirement for applications such as stock tickers, social media notifications, and collaborative editors. Server‑Sent Events (SSE) offer a simple, efficient, HTTP‑based solution for one‑way data streams.
What is Server‑Sent Events
SSE is a unidirectional communication technology built on HTTP that allows a server to continuously push data to a client over a persistent connection. It uses the EventSource API on the client and sends messages in text/event-stream format.
SSE use cases include:
Financial data updates (e.g., stock prices)
Social media real‑time streams
Log monitoring and analysis
Instant notifications (email, task updates)
Collaborative tools (document editing)
Compared with WebSockets, SSE is better suited for one‑way data flow because it works directly over HTTP and requires no additional protocol support, making it lightweight.
SSE Main Advantages
Simple to use: browsers can receive data with EventSource without extra configuration.
Automatic reconnection: browsers handle reconnection natively.
Low resource consumption: runs over an HTTP long‑living connection without extra TCP ports or handshake overhead.
Good compatibility: works with any HTTP‑compatible environment, including CDNs and proxies, and can be combined with caching strategies.
SSE Message Format
SSE sends plain‑text data, ending each message with a double newline \n\n . Example format:
data: This is a regular message
data: {"name": "John", "message": "Hello"}SSE also supports custom event types, allowing the client to listen for different messages:
event: update
data: {"status": "success", "timestamp": "2025-02-13T12:00:00Z"}
event: alert
data: {"message": "系统异常"}On the client side, addEventListener can be used to listen for specific events:
eventSource.addEventListener("update", (event) => {
console.log("更新消息:", event.data);
});The server can provide an id field for resumable streams; the client automatically sends Last-Event-ID on reconnection:
id: 12345
data: 这是一条可以恢复的消息Show Your Code
Below is a complete SSE server written in Go and a JavaScript client.
Server‑side (Go example)
package main
import (
"fmt"
"log"
"net/http"
"time"
)
// SSE handler
func sseHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*") // CORS
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
for {
_, err := fmt.Fprintf(w, "data: 当前时间:%s\n\n", time.Now().Format(time.RFC3339))
if err != nil {
log.Println("客户端连接断开:", err)
break
}
flusher.Flush() // push immediately
time.Sleep(2 * time.Second)
}
}
func main() {
http.HandleFunc("/events", sseHandler)
port := 8080
log.Printf("SSE服务器运行在 http://localhost:%d/events", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}Frontend (JavaScript client)
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
console.log("收到消息:", event.data);
};
eventSource.onerror = () => {
console.log("连接丢失,尝试重连...");
};The browser automatically maintains the SSE connection and attempts reconnection when it drops.
SSE vs. WebSockets
Both technologies enable real‑time data push, but their design goals differ. The table below highlights key differences:
Feature
SSE
WebSocket
Communication
One‑way (server → client)
Two‑way (client ↔ server)
Protocol
HTTP (EventStream)
Custom TCP
Auto‑reconnect
Browser built‑in
Manual implementation
Compatibility
Works with HTTP proxies, CDNs
May be blocked by firewalls/proxies
Typical use cases
Server push (news, logs)
Chat, games, collaborative editing
If an application only needs server‑to‑client pushes (e.g., stock quotes, news feeds), SSE is the better choice; for bidirectional interaction (e.g., online games, WebRTC), WebSockets are more appropriate.
Best Use Cases for SSE
Real‑time data streams: log monitoring, financial data.
Social media feeds: Twitter, Facebook updates.
Notification systems: email alerts, new order notifications.
IoT device monitoring.
Collaborative platforms: Google Docs, Figma.
When the primary requirement is server‑to‑client data push, SSE offers the simplest and most stable solution.
Professional Tips
Optimize long‑living connections: enable keep-alive to prevent timeout.
Load balancing: SSE relies on HTTP long connections; use Nginx with proxy_buffering off; for proper streaming.
Data recovery: use Last-Event-ID so clients can retrieve missed events after reconnection.
CORS: set appropriate headers when the server and client are on different domains.
res.setHeader('Access-Control-Allow-Origin', '*');Conclusion
SSE is a lightweight, easy‑to‑implement real‑time push solution suitable for unidirectional data flow scenarios such as stock markets, news feeds, and social notifications. Compared with WebSockets, SSE is simpler, enjoys native browser support with automatic reconnection, and imposes less server overhead.
If your application only needs server‑to‑client pushes, SSE is an ideal choice; for bidirectional communication, consider WebSockets. Selecting the right technology ensures higher efficiency and stability.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.