diff --git a/context.go b/context.go index 788b00bb..c1a0046e 100644 --- a/context.go +++ b/context.go @@ -1378,11 +1378,22 @@ func (c *Context) SSEvent(name string, message any) { }) } +// InitSSE sets the response headers required for a Server-Sent Events stream +// and flushes them immediately, so the client starts receiving the stream +// without waiting for the first event. +func (c *Context) InitSSE() { + c.Writer.Header().Set("Content-Type", "text/event-stream") + c.Writer.Header().Set("Cache-Control", "no-cache") + c.Writer.Header().Set("Connection", "keep-alive") + c.Writer.WriteHeaderNow() + c.Writer.Flush() +} + // Stream sends a streaming response and returns a boolean // indicates "Is client disconnected in middle of stream" func (c *Context) Stream(step func(w io.Writer) bool) bool { w := c.Writer - clientGone := w.CloseNotify() + clientGone := c.Request.Context().Done() for { select { case <-clientGone: @@ -1397,6 +1408,27 @@ func (c *Context) Stream(step func(w io.Writer) bool) bool { } } +// SSEStream initializes a Server-Sent Events response via InitSSE and then +// repeatedly calls step, flushing after each call, until step returns false +// or the client disconnects. It returns true if the client disconnected +// before step returned false. +func (c *Context) SSEStream(step func(c *Context) bool) bool { + c.InitSSE() + clientGone := c.Request.Context().Done() + for { + select { + case <-clientGone: + return true + default: + keepOpen := step(c) + c.Writer.Flush() + if !keepOpen { + return false + } + } + } +} + /************************************/ /******** CONTENT NEGOTIATION *******/ /************************************/ diff --git a/context_test.go b/context_test.go index cef488c9..66fce727 100644 --- a/context_test.go +++ b/context_test.go @@ -3267,6 +3267,7 @@ func CreateTestResponseRecorder() *TestResponseRecorder { func TestContextStream(t *testing.T) { w := CreateTestResponseRecorder() c, _ := CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) stopStream := true c.Stream(func(w io.Writer) bool { @@ -3287,10 +3288,11 @@ func TestContextStreamWithClientGone(t *testing.T) { w := CreateTestResponseRecorder() c, _ := CreateTestContext(w) + ctx, cancel := context.WithCancel(context.Background()) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) + c.Stream(func(writer io.Writer) bool { - defer func() { - w.closeClient() - }() + defer cancel() _, err := writer.Write([]byte("test")) require.NoError(t, err) @@ -3301,6 +3303,47 @@ func TestContextStreamWithClientGone(t *testing.T) { assert.Equal(t, "test", w.Body.String()) } +func TestContextSSEStream(t *testing.T) { + w := CreateTestResponseRecorder() + c, _ := CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) + + stopStream := true + c.SSEStream(func(c *Context) bool { + defer func() { + stopStream = false + }() + + c.SSEvent("message", "test") + + return stopStream + }) + + assert.Equal(t, "text/event-stream;charset=utf-8", w.Header().Get("Content-Type")) + assert.Equal(t, "no-cache", w.Header().Get("Cache-Control")) + assert.Equal(t, "keep-alive", w.Header().Get("Connection")) + assert.Equal(t, "event:message\ndata:test\n\nevent:message\ndata:test\n\n", w.Body.String()) +} + +func TestContextSSEStreamWithClientGone(t *testing.T) { + w := CreateTestResponseRecorder() + c, _ := CreateTestContext(w) + + ctx, cancel := context.WithCancel(context.Background()) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) + + clientGone := c.SSEStream(func(c *Context) bool { + defer cancel() + + c.SSEvent("message", "test") + + return true + }) + + assert.True(t, clientGone) + assert.Equal(t, "event:message\ndata:test\n\n", w.Body.String()) +} + func TestContextResetInHandler(t *testing.T) { w := CreateTestResponseRecorder() c, _ := CreateTestContext(w)