mirror of
https://github.com/gin-gonic/gin.git
synced 2026-07-14 07:07:03 +08:00
fix: fallback to Request.Context in Context
.Stream when CloseNotify is nil
This commit is contained in:
parent
1f5552f6d2
commit
3317f91a1b
@ -1328,10 +1328,16 @@ func (c *Context) SSEvent(name string, message any) {
|
|||||||
func (c *Context) Stream(step func(w io.Writer) bool) bool {
|
func (c *Context) Stream(step func(w io.Writer) bool) bool {
|
||||||
w := c.Writer
|
w := c.Writer
|
||||||
clientGone := w.CloseNotify()
|
clientGone := w.CloseNotify()
|
||||||
|
var requestGone <-chan struct{}
|
||||||
|
if c.Request != nil {
|
||||||
|
requestGone = c.Request.Context().Done()
|
||||||
|
}
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-clientGone:
|
case <-clientGone:
|
||||||
return true
|
return true
|
||||||
|
case <-requestGone:
|
||||||
|
return true
|
||||||
default:
|
default:
|
||||||
keepOpen := step(w)
|
keepOpen := step(w)
|
||||||
w.Flush()
|
w.Flush()
|
||||||
|
|||||||
@ -3078,6 +3078,25 @@ func TestContextStreamWithClientGone(t *testing.T) {
|
|||||||
assert.Equal(t, "test", w.Body.String())
|
assert.Equal(t, "test", w.Body.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestContextStreamWithRequestContextDone(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := CreateTestContext(w)
|
||||||
|
|
||||||
|
reqCtx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil).WithContext(reqCtx)
|
||||||
|
|
||||||
|
disconnected := c.Stream(func(writer io.Writer) bool {
|
||||||
|
_, err := writer.Write([]byte("test"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.True(t, disconnected)
|
||||||
|
assert.Empty(t, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
func TestContextResetInHandler(t *testing.T) {
|
func TestContextResetInHandler(t *testing.T) {
|
||||||
w := CreateTestResponseRecorder()
|
w := CreateTestResponseRecorder()
|
||||||
c, _ := CreateTestContext(w)
|
c, _ := CreateTestContext(w)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user