From cb301401d3ac24cd228db8a389932fefd406e077 Mon Sep 17 00:00:00 2001 From: Hristo Trendev Date: Sun, 12 Jan 2025 06:11:30 +0100 Subject: [PATCH] feat: add support for server-sent events (#72) --- example/example.go | 9 +++++++++ gzip.go | 5 +++++ handler.go | 3 +-- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/example/example.go b/example/example.go index e0a930f..f48828c 100644 --- a/example/example.go +++ b/example/example.go @@ -16,6 +16,15 @@ func main() { r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) }) + r.GET("/stream", func(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + c.Header("Connection", "keep-alive") + for i := 0; i < 10; i++ { + fmt.Fprintf(c.Writer, "id: %d\ndata: tick %d\n\n", i, time.Now().Unix()) + c.Writer.Flush() + time.Sleep(1 * time.Second) + } + }) // Listen and Server in 0.0.0.0:8080 if err := r.Run(":8080"); err != nil { diff --git a/gzip.go b/gzip.go index 529c62d..c2299a2 100644 --- a/gzip.go +++ b/gzip.go @@ -32,6 +32,11 @@ func (g *gzipWriter) Write(data []byte) (int, error) { return g.writer.Write(data) } +func (g *gzipWriter) Flush() { + _ = g.writer.Flush() + g.ResponseWriter.Flush() +} + // Fix: https://github.com/mholt/caddy/issues/38 func (g *gzipWriter) WriteHeader(code int) { g.Header().Del("Content-Length") diff --git a/handler.go b/handler.go index ee9eb9f..990090c 100644 --- a/handler.go +++ b/handler.go @@ -66,8 +66,7 @@ func (g *gzipHandler) Handle(c *gin.Context) { func (g *gzipHandler) shouldCompress(req *http.Request) bool { if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") || - strings.Contains(req.Header.Get("Connection"), "Upgrade") || - strings.Contains(req.Header.Get("Accept"), "text/event-stream") { + strings.Contains(req.Header.Get("Connection"), "Upgrade") { return false }