Gin in production · 5 MIN READ

Server-Sent Events in Gin: flush every event, send heartbeats, stop on the request context

Stream SSE from a Gin handler that flushes events, sends heartbeats, ends when the client leaves and survives http.Server's WriteTimeout.

Server-Sent Events keep one HTTP response open and append small text events to it; the browser's EventSource parses them and reconnects on its own. The protocol is simple, and the engineering is all in the lifecycle. Every event must be flushed through buffers, idle streams need heartbeats, the handler must notice when the client leaves, and the server's write deadline must not cut the stream short.

gin · A MAP OF THE IDEA

  1. Set headers, flush
  2. Select ctx, feed, beat
  3. SSEvent + Flush
  4. Extend write deadline

Useful when

  • Plain HTTP: works through proxies, with automatic reconnects.
  • An explicit select loop is deterministic under httptest.

Watch out

  • WriteTimeout cuts long streams unless you set per-write deadlines.
  • Shutdown does not cancel streams; give them a stop signal.

Implementation & operation cost: One goroutine and one connection per subscriber for the whole session, plus a replay store if clients must resume without gaps.

01

The wire format and what c.SSEvent writes

An event is a group of field lines ended by a blank line: event: names it, data: carries the payload, and optional id: and retry: lines support reconnection. A line that starts with a colon is a comment that EventSource ignores, which makes it a cheap heartbeat. In Gin v1.12.0, c.SSEvent(name, data) renders through gin-contrib/sse. It sets Content-Type to text/event-stream;charset=utf-8, sets Cache-Control: no-cache unless a value is already present, writes the event: and data: lines, turns newlines inside string data into extra data: lines, and JSON-encodes structs, maps and slices. It never writes an id: line. It also mostly swallows write failures: string payloads ignore them, and a failed JSON write only lands in c.Errors. The handler therefore cannot learn from SSEvent that the client has gone, and has to watch the request context instead.

02

What c.Stream does, read from the source

c.Stream(step) loops: it checks the channel returned by c.Writer.CloseNotify(), calls step, flushes, and stops when step returns false. Two consequences follow from the v1.12.0 code. Gin's CloseNotify is an unchecked type assertion on the underlying writer, and httptest.ResponseRecorder does not implement http.CloseNotifier, so under a recorder c.Stream panics with a missing method CloseNotify error. Disconnects are also checked only between steps, so a step that blocks waiting for the next event leaves a departed client unnoticed until something is published. net/http deprecates CloseNotifier in favor of Request.Context for exactly this reason. On a real server c.Stream works if the step itself selects on the request context.

go
ctx := c.Request.Context()
clientGone := c.Stream(func(w io.Writer) bool {
	select {
	case <-ctx.Done():
		return false // without this case, a blocked step never sees the disconnect
	case ev, ok := <-feed:
		if !ok {
			return false
		}
		c.SSEvent(ev.Name, ev.Data)
		return true // Stream flushes after every step
	}
})
Read the code

This fragment runs inside a handler on a real http.Server in your own environment, where the response writer implements CloseNotify. The select inside step makes a disconnect end the stream immediately instead of at the next event. The boolean result reports whether Stream saw CloseNotify fire. Under httptest.NewRecorder the same handler panics before step is ever called, which is why the tested version below uses its own loop.

03

An explicit loop that tests cleanly

The handler below does the same work with one select over the request context, the event feed and a heartbeat channel. It commits headers with an early flush and uses http.ResponseController to replace the server-wide WriteTimeout with a deadline per write. The test feeds the handler from one goroutine over unbuffered channels, so exactly one select case is ready at any moment and the output is deterministic. Canceling the request context simulates the client disconnecting.

go
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/gin-gonic/gin"
)

type Event struct {
	Name string
	Data any
}

// events delivers published events; beats is a ticker channel in production.
func events(feed <-chan Event, beats <-chan time.Time, writeBudget time.Duration) gin.HandlerFunc {
	return func(c *gin.Context) {
		rc := http.NewResponseController(c.Writer)
		extend := func() bool {
			// Replace the server-wide WriteTimeout with a per-write budget.
			err := rc.SetWriteDeadline(time.Now().Add(writeBudget))
			return err == nil || errors.Is(err, http.ErrNotSupported)
		}
		c.Header("Content-Type", "text/event-stream")
		c.Header("Cache-Control", "no-cache")
		c.Status(http.StatusOK)
		if !extend() {
			return
		}
		c.Writer.Flush() // commit headers: the client now knows the stream is open

		ctx := c.Request.Context()
		for {
			select {
			case <-ctx.Done():
				return // client gone, or the server is canceling requests
			case ev, ok := <-feed:
				if !ok || !extend() {
					return
				}
				c.SSEvent(ev.Name, ev.Data)
				c.Writer.Flush()
			case <-beats:
				if !extend() {
					return
				}
				if _, err := io.WriteString(c.Writer, ": ping\n\n"); err != nil {
					return
				}
				c.Writer.Flush()
			}
		}
	}
}

func main() {
	gin.SetMode(gin.TestMode)
	feed := make(chan Event)
	beats := make(chan time.Time)
	r := gin.New()
	r.GET("/events", events(feed, beats, 10*time.Second))

	ctx, disconnect := context.WithCancel(context.Background())
	req := httptest.NewRequest("GET", "/events", nil).WithContext(ctx)
	go func() {
		// Unbuffered sends: exactly one select case is ready at a time.
		feed <- Event{"note", "line one\nline two"}
		beats <- time.Time{}
		feed <- Event{"price", gin.H{"cents": 4200, "symbol": "GO"}}
		disconnect()
	}()
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req) // returns once the handler sees ctx.Done()

	res := w.Result()
	fmt.Println(res.StatusCode, res.Header.Get("Content-Type"), res.Header.Get("Cache-Control"), "flushed:", w.Flushed)
	fmt.Print(w.Body.String())
	err := http.NewResponseController(w).SetWriteDeadline(time.Now())
	fmt.Println("recorder supports write deadlines:", !errors.Is(err, http.ErrNotSupported))
}
Read the code

The Flush before the first event sends the status and headers, so EventSource fires its open event right away instead of waiting for data. The two-line note becomes two data: lines, the gin.H value is JSON-encoded with sorted keys, and : ping is a comment the browser discards. Result() reports the headers as they were when first written, so it shows the handler's text/event-stream rather than the variant SSEvent later writes into the header map. After disconnect(), ctx.Done is the only ready case, so the handler and ServeHTTP return. The last line shows that the recorder cannot set write deadlines: SetWriteDeadline returns an error matching http.ErrNotSupported, which the handler tolerates. The deadline itself needs a native integration test.

04

WriteTimeout, proxies and shutdown

http.Server.WriteTimeout sets one deadline on the connection after the request headers are read, and writes do not extend it. A stream that outlives it gets write errors, and clients reconnect in a loop at exactly that interval. Setting WriteTimeout to zero for the whole server removes the protection from every normal route. Instead, call SetWriteDeadline on a ResponseController before each write. The stream can then last for hours, while a client that stops reading can hold the goroutine for at most one write budget. This works through Gin's writer because ResponseController follows its Unwrap method. Heartbeats every 15 to 30 seconds keep load balancers with idle timeouts from closing quiet streams, and buffering proxies need buffering disabled for the route, for example nginx's X-Accel-Buffering: no response header. Shutdown waits for active connections to go idle and does not cancel request contexts, so an open stream blocks it until the shutdown budget expires. Use RegisterOnShutdown to close a stop channel that every stream loop selects on.

05

Resume, fan-out and limits

EventSource reconnects automatically and sends Last-Event-ID with the last id: it received. Resuming without gaps needs IDs from a durable sequence that the server can replay from. Because c.SSEvent has no id parameter, write the id: line yourself, or render a gin-contrib/sse Event with Id set through c.Render. Each stream costs one goroutine and one connection, so cap concurrent streams per user and in total; a reload loop or a forgotten tab adds up quickly. Over HTTP/1.1, browsers allow about six connections per origin across all tabs, while HTTP/2 multiplexes streams over one connection. With in-process fan-out, a slow subscriber must not block the publisher: give each subscriber a small buffered channel and disconnect it when the buffer is full, then let it resume from Last-Event-ID. Test event formatting including newlines, heartbeats, a disconnect, a closed feed and a shutdown signal, and verify write deadlines against a real listener.

TAKE THIS WITH YOU

Commit headers with a flush, write each event with c.SSEvent and flush it, send comment heartbeats, and select on c.Request.Context().Done() instead of relying on c.Stream's CloseNotify check. Replace the server-wide WriteTimeout with a per-write deadline from ResponseController.

Check your understanding

What happens in Gin v1.12.0 when a handler that calls c.Stream is exercised with httptest.NewRecorder()?

Go to the source

Progress stays in this browser. No account needed.