mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
feat: add InitSSE/SSEStream helpers and stop using deprecated CloseNotifier in Stream
Fixes #4661 - Context.InitSSE sets the standard SSE response headers and flushes them immediately, removing the boilerplate every SSE handler had to repeat. - Context.SSEStream pairs InitSSE with a Stream-like loop so SSE handlers no longer need to duplicate the disconnect-handling logic. - Context.Stream now detects client disconnects via Request.Context().Done() instead of the deprecated http.CloseNotifier, matching net/http's recommended replacement.
This commit is contained in:
parent
3b08cd7235
commit
049d789e48
34
context.go
34
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 *******/
|
||||
/************************************/
|
||||
|
||||
@ -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)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user