-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsse_client.go
More file actions
70 lines (57 loc) · 1.65 KB
/
sse_client.go
File metadata and controls
70 lines (57 loc) · 1.65 KB
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
// Package main contains an SSE client example.
package main
import (
"bufio"
"context"
"fmt"
"log"
"net/http"
"strings"
)
//nolint:gocyclo // example client with multiple error handling paths
func main() {
callbackToken := "example-token-123"
url := fmt.Sprintf("http://localhost:3011/events?callbackToken=%s", callbackToken)
// Create request with optional Last-Event-ID for catchup
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
log.Fatal(err)
}
// Uncomment to test catchup from specific timestamp (nanoseconds)
// req.Header.Set("Last-Event-ID", "1699632000000000000")
req.Header.Set("Accept", "text/event-stream")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
log.Fatalf("Failed to connect: %d", resp.StatusCode)
}
log.Println("Connected to SSE stream...")
scanner := bufio.NewScanner(resp.Body)
var eventID, eventType, eventData string
for scanner.Scan() {
line := scanner.Text()
if line == "" {
// Empty line signals end of event
if eventData != "" {
log.Printf("[ID: %s] [Type: %s] %s\n", eventID, eventType, eventData)
eventID, eventType, eventData = "", "", ""
}
continue
}
if strings.HasPrefix(line, "id: ") {
eventID = strings.TrimPrefix(line, "id: ")
} else if strings.HasPrefix(line, "event: ") {
eventType = strings.TrimPrefix(line, "event: ")
} else if strings.HasPrefix(line, "data: ") {
eventData = strings.TrimPrefix(line, "data: ")
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}