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 7de33eb..a2a75cc 100644 --- a/handler.go +++ b/handler.go @@ -62,8 +62,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 }