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

sse client #658

Open
chrisfeng0723 opened this issue May 8, 2023 · 6 comments
Open

sse client #658

chrisfeng0723 opened this issue May 8, 2023 · 6 comments

Comments

@chrisfeng0723
Copy link

I simulated an SSE client with net/http and can receive pushes from the SSE server. However, with resty, the data is pushed all at once. The code is as follows. Do I need any other settings?

       client := resty.New()
	resp, err := client.R().
		EnableTrace().
		SetHeader("Content-Type", "application/json").
		SetBody(value).
		Post("localhost:8080/stream")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.RawBody().Close()
	
	reader := bufio.NewReader(resp.RawBody())
	for {

		line, err := reader.ReadString('\n')
		if err != nil {
			break
		}
		fmt.Println(line)
	}
@xuji-cny
Copy link

I have the same doubt

@xiaziheng98
Copy link

I have the same doubt too

@jeevatkm
Copy link
Member

@chrisfeng0723 In resty response, body read fully at once. It is not a stream. Maybe you could try https://pkg.go.dev/github.com/go-resty/resty/v2#Request.SetDoNotParseResponse and handle the body yourself. However, it will not be an actual SSE experience.

I may think of adding an SSE client in the v3.

@gospider007
Copy link

@CermakM
Copy link

CermakM commented Feb 20, 2024

SSE client would be very appreciated! 🙏

@sosyz
Copy link

sosyz commented Apr 17, 2024

maybe this code can help you

func TestSSE(t *testing.T) {
	// Start the server
	go func() {
		err := http.ListenAndServe(":5000", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "text/event-stream")
			w.Header().Set("Cache-Control", "no-cache")
			w.Header().Set("Connection", "keep-alive")
			for i := 0; i < 3; i++ {
				_, err := w.Write([]byte(fmt.Sprintf("%d\n", i)))
				if err != nil {
					t.Log("Error writing SSE event:", err)
					return
				}

				if f, ok := w.(http.Flusher); ok {
					f.Flush()
				}
				time.Sleep(1 * time.Second)
			}
		}))
		if err != nil {
			t.Error(err)
		}
	}()
	time.Sleep(time.Second * 3)

	resp, err := resty.New().
		R().
		SetDoNotParseResponse(true).
		Get("http://localhost:5000")
	if err != nil {
		t.Error(err)
	}
	defer resp.RawResponse.Body.Close()

	scanner := bufio.NewScanner(resp.RawResponse.Body)
	reply := ""
	for scanner.Scan() {
		_res := scanner.Text()
		if _res == "" {
			continue
		}
		reply += _res
		t.Log(_res)
	}

	t.Log(reply)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

7 participants