-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
sse.go
105 lines (92 loc) · 2.29 KB
/
sse.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package client
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"net/textproto"
"strings"
)
type SSE struct {
Close func() error
Next func(response interface{}) error
}
type SSEResponse struct {
Data interface{} `json:"data"`
Label string `json:"label"`
Path []interface{} `json:"path"`
HasNext bool `json:"hasNext"`
Errors json.RawMessage `json:"errors"`
Extensions map[string]interface{} `json:"extensions"`
}
func errorSSE(err error) *SSE {
return &SSE{
Close: func() error { return nil },
Next: func(response interface{}) error {
return err
},
}
}
func (p *Client) SSE(ctx context.Context, query string, options ...Option) *SSE {
r, err := p.newRequest(query, options...)
if err != nil {
return errorSSE(fmt.Errorf("request: %w", err))
}
r = r.WithContext(ctx)
r.Header.Set("Accept", "text/event-stream")
r.Header.Set("Cache-Control", "no-cache")
r.Header.Set("Connection", "keep-alive")
srv := httptest.NewServer(p.h)
w := httptest.NewRecorder()
p.h.ServeHTTP(w, r)
reader := textproto.NewReader(bufio.NewReader(w.Body))
line, err := reader.ReadLine()
if err != nil {
return errorSSE(fmt.Errorf("response: %w", err))
}
if line != ":" {
return errorSSE(fmt.Errorf("expected :, got %s", line))
}
return &SSE{
Close: func() error {
srv.Close()
return nil
},
Next: func(response interface{}) error {
for {
line, err := reader.ReadLine()
if err != nil {
return err
}
kv := strings.SplitN(line, ": ", 2)
switch kv[0] {
case "":
continue
case "event":
switch kv[1] {
case "next":
continue
case "complete":
return nil
default:
return fmt.Errorf("expected event type: %#v", kv[1])
}
case "data":
var respDataRaw SSEResponse
if err = json.Unmarshal([]byte(kv[1]), &respDataRaw); err != nil {
return fmt.Errorf("decode: %w", err)
}
// we want to unpack even if there is an error, so we can see partial responses
unpackErr := unpack(respDataRaw, response)
if respDataRaw.Errors != nil {
return RawJsonError{respDataRaw.Errors}
}
return unpackErr
default:
return fmt.Errorf("unexpected sse field %s", kv[0])
}
}
},
}
}