-
Notifications
You must be signed in to change notification settings - Fork 27
/
sse_test.go
72 lines (69 loc) · 1.61 KB
/
sse_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"io"
"log"
"net/http"
"testing"
"time"
"github.com/gospider007/requests"
)
func TestSse(t *testing.T) {
// Start the server
go func() {
err := http.ListenAndServe(":3333", 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")
w.Header().Set("Access-Control-Allow-Origin", "*")
// SSE event format
event := "message"
data := "testing"
// Start SSE loop
for i := 0; i < 3; i++ {
// Send SSE event
_, err := w.Write([]byte("event: " + event + "\n"))
if err != nil {
log.Println("Error writing SSE event:", err)
return
}
_, err = w.Write([]byte("data: " + data + "\n\n"))
if err != nil {
log.Println("Error writing SSE data:", err)
return
}
// Flush the response writer
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
// Delay before sending the next event
time.Sleep(1 * time.Second)
}
}))
if err != nil {
t.Error(err)
}
}()
time.Sleep(time.Second * 3)
response, err := requests.Get(nil, "http://127.0.0.1:3333/events") // Send WebSocket request
if err != nil {
t.Error(err)
}
defer response.CloseBody()
sseCli := response.SSE()
defer sseCli.Close()
if sseCli == nil {
t.Error("not is sseCli")
}
for {
data, err := sseCli.Recv()
if err != nil {
if err != io.EOF {
t.Error(err)
}
break
}
if data.Data != "testing" {
t.Error("testing")
}
}
}