Skip to content

Commit

Permalink
feat: add support for server-sent events (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
htrendev authored Jan 12, 2025
1 parent 071dbd1 commit cb30140
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
9 changes: 9 additions & 0 deletions example/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
3 changes: 1 addition & 2 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down

0 comments on commit cb30140

Please sign in to comment.