go 50 lines · 10 steps

Streaming a live log tail with SSE in Gin

A Gin handler that tails a file and pushes each new line to the client over Server-Sent Events.

Explained by highlit
1func StreamLogs(c *gin.Context) {
2 path := c.Query("file")
3 if path == "" {
4 c.JSON(http.StatusBadRequest, gin.H{"error": "missing file parameter"})
5 return
6 }
7 
8 t, err := tail.TailFile(path, tail.Config{
9 Follow: true,
10 ReOpen: true,
11 MustExist: true,
12 Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekEnd},
13 })
14 if err != nil {
15 c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
16 return
17 }
18 defer t.Stop()
19 
20 c.Writer.Header().Set("Content-Type", "text/event-stream")
21 c.Writer.Header().Set("Cache-Control", "no-cache")
22 c.Writer.Header().Set("Connection", "keep-alive")
23 
24 heartbeat := time.NewTicker(15 * time.Second)
25 defer heartbeat.Stop()
26 
27 ctx := c.Request.Context()
28 c.Stream(func(w io.Writer) bool {
29 select {
30 case <-ctx.Done():
31 return false
32 case line, ok := <-t.Lines:
33 if !ok {
34 return false
35 }
36 if line.Err != nil {
37 c.SSEvent("error", line.Err.Error())
38 return true
39 }
40 c.SSEvent("log", gin.H{
41 "time": line.Time.Format(time.RFC3339),
42 "text": line.Text,
43 })
44 return true
45 case <-heartbeat.C:
46 c.SSEvent("ping", time.Now().Unix())
47 return true
48 }
49 })
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Server-Sent Events let a single long-lived HTTP response push updates as they happen, no polling required.
  2. 2Watching the request context inside a stream loop is how you detect a disconnected client and stop cleanly.
  3. 3A periodic heartbeat keeps idle SSE connections alive through proxies and timeouts.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Streaming a live log tail with SSE in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code