Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why can't I receive the ctx.Done() signal in ctx.stream when closing the client connection when using SSE long connection? #4082

Open
ppd324 opened this issue Oct 25, 2024 · 0 comments

Comments

@ppd324
Copy link

ppd324 commented Oct 25, 2024

  • With issues:
    • Why can't I receive the ctx.Done() signal in ctx.stream when closing the client connection when using SSE long connection?

Description

When I close the sse long connection, ctx.Done() cannot receive the signal, causing the connection to not be released.

How to reproduce

ctx.Writer.Header().Set("Content-Type", "text/event-stream")
	ctx.Writer.Header().Set("Cache-Control", "no-cache")
	ctx.Writer.Header().Set("Connection", "keep-alive")
	ctx.Writer.Header().Set("Transfer-Encoding", "chunked")
	ctx.Writer.Header().Set("X-Accel-Buffering", "no")
	fmt.Fprintf(ctx.Writer, "data: %s\n\n", "connected")
	ctx.Writer.Flush()
	ctx.Stream(func(w io.Writer) bool {
		select {
		case <-ctx.Request.Context().Done():
			w.Write([]byte("data:[done]\n\n"))
			log.Info("capture result listen done")
			return false
		case cr := <-newChan:
			if cr == nil {
				return false
			}
			data, err := json.Marshal(cr)
			if err != nil {
				log.Errorf("marshal capture result failed, err: %v", err)
				return false
			}
			_, err = fmt.Fprintf(w, "data: %s\n\n", data)
			if err != nil {
				log.Errorf("write capture result failed, err: %v", err)
				return false
			}
			w.(http.Flusher).Flush()
			return true
		}
	})

Expectations

When closing the client connection, print"capture result listen done"

Actual result

After the connection is closed, only failure to send again will trigger the end of the loop.

Environment

  • go version: 1.22.0
  • gin version (or commit ref): 1.9.1
  • operating system: linux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant