Go Server-Sent Events: Live Updates Over HTTP

Updated 9 min read
Go Server-Sent Events featured image: cards for the event stream, flushing and auto reconnect

Go Server-Sent Events let a server push live updates to a browser over a plain HTTP connection. In this post, you will learn how the event stream format works and why it is often simpler than WebSockets. Then we will build an order tracker that sends updates to every open page the moment they happen.

This lesson follows on from Go WebSockets for a real-time chat server, so you can compare both tools. We also use channels from Go channels explained with examples and the select statement from the Go select statement lesson.

What Are Go Server-Sent Events?

In short, Server-Sent Events, or SSE, is a web standard for one-way streaming from a server to a browser. First, the browser opens a normal GET request. Then the server simply never finishes the response. Instead, it keeps writing small text messages whenever something new happens.

For example, think of a radio station. You tune in once, and then the station keeps talking. However, you cannot talk back through the radio. Similarly, with SSE the server talks and the browser listens.

The best part is that Go Server-Sent Events need no extra package. In fact, everything comes from net/http in the standard library.

Why Go Server-Sent Events Matter

However, many “live” features only need data flowing one way. In those cases, WebSockets add more moving parts than you need. For example, here are typical uses of Go Server-Sent Events.

  • Order or delivery tracking: the page updates when the status changes, so the customer never refreshes.
  • Notifications: a new comment or message shows a badge right away.
  • Live scores and prices: numbers change on screen as soon as the server knows.
  • Progress bars: a long export job reports 10%, 20% and so on.
  • AI chat replies: many chat apps stream answers word by word with SSE.

In short, choose Go Server-Sent Events whenever the server talks and the browser mostly listens.

How Go Server-Sent Events Work

First, the browser creates an EventSource that points at a URL. Next, the server answers with the header Content-Type: text/event-stream and keeps the connection open. Then, every time there is news, the server writes a few text lines followed by a blank line. Finally, the browser fires an event for each block it receives.

Go Server-Sent Events diagram showing one open GET request carrying a stream of text events
The browser opens one GET request, and the server keeps it open, writing a new text event block each time something changes.

Also, the browser handles reconnects for you. If the connection drops, EventSource waits a moment and connects again. Also, the last event ID travels in a Last-Event-ID header, so the server can resend anything the user missed.

The Event Stream Format

In the stream, each message is plain text. So every line has a field name, a colon and a value. Then a blank line ends the message. This table shows the fields you can use.

FieldExampleMeaning
datadata: {"order":1042}The message body, often JSON
eventevent: orderA custom event name for the browser
idid: 7An ID the browser remembers for reconnects
retryretry: 3000Wait time in milliseconds before reconnecting
: comment: keep-aliveIgnored by the browser, useful as a heartbeat

For instance, one complete message looks like this.

id: 1
event: order
data: {"order":1042,"status":"paid"}

Clearly, the empty line at the end matters. Without it, the browser keeps waiting and never fires the event.

Go Server-Sent Events vs WebSockets

Both tools deliver live data. However, they solve slightly different problems. The table below compares them.

FeatureServer-Sent EventsWebSockets
DirectionServer to browser onlyBoth ways
ProtocolPlain HTTPUpgrade to a new protocol
Extra Go packageNoneUsually one
Auto reconnectBuilt into the browserYou write it yourself
Data typeText onlyText or binary
Works with HTTP tools and proxiesYes, easilyNeeds upgrade support
Server-Sent Events vs WebSockets diagram comparing direction, protocol and reconnects
SSE sends events one way over normal HTTP with automatic reconnects, while WebSockets carry messages both ways after an upgrade.

So when should you use which? Pick Server-Sent Events for feeds, alerts and progress updates. On the other hand, pick WebSockets for chat, games and other features where the browser also sends a lot.

Hands-On: Build a Live Order Tracker

Now let’s build a small service with Go Server-Sent Events. A POST /publish request announces an order update, and every browser connected to GET /events receives it instantly.

Step 1: A Broker for Subscribers

Here, the broker keeps one channel per connected browser. As a result, publishing a message means sending it into every channel.

// Broker keeps one channel per connected client.
type Broker struct {
	mu      sync.Mutex
	clients map[chan string]struct{}
}

func NewBroker() *Broker {
	return &Broker{clients: make(map[chan string]struct{})}
}

func (b *Broker) subscribe() chan string {
	ch := make(chan string, 10)
	b.mu.Lock()
	b.clients[ch] = struct{}{}
	b.mu.Unlock()
	return ch
}

func (b *Broker) unsubscribe(ch chan string) {
	b.mu.Lock()
	delete(b.clients, ch)
	b.mu.Unlock()
}

func (b *Broker) publish(msg string) {
	b.mu.Lock()
	defer b.mu.Unlock()
	for ch := range b.clients {
		select {
		case ch <- msg:
		default: // client is too slow, skip this message
		}
	}
}

Notice that each channel has a buffer of 10 messages. Also, the select with a default case never blocks. So if one browser falls behind, the broker skips it instead of freezing everyone else.

Step 2: The Event Stream Handler

This handler sets the SSE headers and subscribes to the broker. After that, it writes events until the browser leaves.

func (b *Broker) events(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")

	rc := http.NewResponseController(w)
	rc.SetWriteDeadline(time.Time{}) // no write timeout for this stream

	ch := b.subscribe()
	defer b.unsubscribe(ch)

	fmt.Fprint(w, "retry: 3000\n\n")
	rc.Flush()

	id := 0
	for {
		select {
		case <-r.Context().Done():
			log.Println("client disconnected")
			return
		case msg := <-ch:
			id++
			fmt.Fprintf(w, "id: %d\nevent: order\ndata: %s\n\n", id, msg)
			if err := rc.Flush(); err != nil {
				return
			}
		}
	}
}

Let’s look at the important lines. First, http.NewResponseController gives access to Flush, which pushes the bytes to the browser right away. Without it, Go would hold them in a buffer. Next, SetWriteDeadline(time.Time{}) removes the server’s write timeout for this one request. Then r.Context().Done() fires when the browser closes the tab, so the loop ends and the deferred unsubscribe runs.

Step 3: Publishing and Starting the Server

Finally, we add a tiny publish endpoint and start the server with a normal write timeout.

func (b *Broker) publishHandler(w http.ResponseWriter, r *http.Request) {
	b.publish(r.FormValue("msg"))
	fmt.Fprintln(w, "sent")
}

func main() {
	b := NewBroker()
	mux := http.NewServeMux()
	mux.HandleFunc("GET /events", b.events)
	mux.HandleFunc("POST /publish", b.publishHandler)
	srv := &http.Server{Addr: ":8080", Handler: mux, WriteTimeout: 10 * time.Second}
	log.Println("SSE server on :8080")
	log.Fatal(srv.ListenAndServe())
}

Step 4: Test It with curl

First, open one terminal and listen to the stream. The -N flag turns off curl’s buffering, so lines appear as they arrive.

curl -N localhost:8080/events

Then, in a second terminal, publish two updates.

curl -X POST -d 'msg={"order":1042,"status":"paid"}' localhost:8080/publish
curl -X POST -d 'msg={"order":1043,"status":"shipped"}' localhost:8080/publish

The first terminal now shows the full stream, exactly as the server wrote it.

retry: 3000

id: 1
event: order
data: {"order":1042,"status":"paid"}

id: 2
event: order
data: {"order":1043,"status":"shipped"}

We ran this test and the stream stayed open well past the 10 second WriteTimeout. However, when we removed the SetWriteDeadline line, curl stopped after exactly 10 seconds with a partial transfer error. So that one line really matters.

Step 5: Listen in the Browser

In a web page, EventSource does the reading and reconnecting for you, so the code stays short.

<ul id="orders"></ul>
<script>
  const es = new EventSource("/events");
  es.addEventListener("order", (e) => {
    const order = JSON.parse(e.data);
    const li = document.createElement("li");
    li.textContent = "Order " + order.order + " is " + order.status;
    document.getElementById("orders").appendChild(li);
  });
</script>

Because our server sends event: order, the page listens with addEventListener("order", ...). By contrast, messages without an event line arrive in es.onmessage.

Resuming After a Reconnect

When the network drops, the browser reconnects on its own. Then it sends the last ID it saw in the Last-Event-ID request header. As a result, your handler can send only the events the user missed.

func lastEventID(r *http.Request) int {
	n, err := strconv.Atoi(r.Header.Get("Last-Event-ID"))
	if err != nil {
		return 0 // first visit, or no ID yet
	}
	return n
}

For example, say the browser reports ID 41. Then you load events 42 and later from your database and send them first. After that, the handler switches to live events as usual. In our tracker, IDs start again at 1 for each connection. So a real app should use IDs that come from the database.

Scaling Go Server-Sent Events

Each open stream is one goroutine and one channel, which is cheap in Go. So a single small server can hold thousands of listeners. However, our broker lives in memory, just like the chat hub in the WebSockets post.

Therefore, if you run several servers, an update published on one server never reaches browsers on another. The fix is the same as before. Each server subscribes to a shared message system and forwards messages to its own Go Server-Sent Events clients.

Common Mistakes with Go Server-Sent Events

  • Forgetting to flush: events sit in a buffer and appear in bursts. So call Flush after every message.
  • Leaving the write timeout on: the stream dies after the server’s WriteTimeout. Clear it per request with SetWriteDeadline(time.Time{}).
  • Missing the blank line: the browser never fires the event. Always end each message with \n\n.
  • Ignoring the request context: closed tabs leave goroutines running forever. Watch r.Context().Done() in the loop.
  • Blocking on slow clients: one stuck browser freezes every publish. Use buffered channels with a default case.

Best Practices for Go Server-Sent Events

  • Send JSON in the data field, because it keeps messages easy to parse in JavaScript.
  • **Set an id on every event**, so reconnecting browsers can ask for what they missed.
  • Send a comment line every 30 seconds, as some proxies close quiet connections.
  • Use HTTP/2 in production, since browsers limit HTTP/1.1 to about six connections per site.
  • Keep messages small, and send IDs or links rather than whole records.

Practice Task

To practise Go Server-Sent Events, add a heartbeat to the handler. Every 15 seconds, write the comment line : ping followed by a blank line, even when no orders arrive.

Hint: create a time.Ticker and add one more case to the select.

Official Resources

These pages explain the exact API and the event stream rules, so keep them close while you build.

Quick Recap

  • Go Server-Sent Events stream updates from server to browser over plain HTTP.
  • Each message is text lines like data: and id:, ended by a blank line.
  • http.NewResponseController lets you flush and clear the write deadline.
  • A broker with one buffered channel per client handles many listeners.
  • The browser’s EventSource reconnects on its own and resends the last ID.
  • Use SSE for one-way feeds and WebSockets for two-way features.

What’s Next?

However, our broker only works inside one server process. Next, we will connect many services with a real message system: NATS.

Next lesson: Go NATS Messaging: Publish, Subscribe and Request