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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Server-Sent Events let a single long-lived HTTP response push updates as they happen, no polling required.
- 2Watching the request context inside a stream loop is how you detect a disconnected client and stop cleanly.
- 3A periodic heartbeat keeps idle SSE connections alive through proxies and timeouts.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-a-live-log-tail-with-sse-in-gin-explained-go-b393/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.