diff --git a/context.go b/context.go index 582d00f2..346e881a 100644 --- a/context.go +++ b/context.go @@ -1377,11 +1377,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: @@ -1396,6 +1407,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 b82e04d5..f3db0321 100644 --- a/context_test.go +++ b/context_test.go @@ -3270,27 +3270,18 @@ func TestContextRenderDataFromReaderNoHeaders(t *testing.T) { type TestResponseRecorder struct { *httptest.ResponseRecorder - closeChannel chan bool -} - -func (r *TestResponseRecorder) CloseNotify() <-chan bool { - return r.closeChannel -} - -func (r *TestResponseRecorder) closeClient() { - r.closeChannel <- true } func CreateTestResponseRecorder() *TestResponseRecorder { return &TestResponseRecorder{ httptest.NewRecorder(), - make(chan bool, 1), } } 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 { @@ -3311,10 +3302,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) @@ -3325,6 +3317,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)