-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.go
More file actions
213 lines (190 loc) · 4.68 KB
/
Copy pathstream.go
File metadata and controls
213 lines (190 loc) · 4.68 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package httpstream
import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// Event represents a parsed Server-Sent Event (SSE).
type Event struct {
ID string
Event string
Data string
}
// ErrStreamTimeout is returned when no data is received within the IdleTimeout limit.
var ErrStreamTimeout = errors.New("httpstream: idle timeout exceeded")
// Stream executes the HTTP request and returns a raw readable response stream (io.ReadCloser).
func (r *Request) Stream() (io.ReadCloser, error) {
resp, err := r.Send()
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("httpstream status non-OK: %d", resp.StatusCode)
}
return resp.Body, nil
}
// StreamLines executes the HTTP request and invokes the callback sequentially for each line.
// This is suitable for reading custom line-delimited raw text streams (like logs or stdout).
func (r *Request) StreamLines(callback func(line string) error) error {
resp, err := r.Stream()
if err != nil {
return err
}
defer resp.Close()
var timeoutErr error
var timer *time.Timer
if r.idleTimeout > 0 {
timer = time.AfterFunc(r.idleTimeout, func() {
timeoutErr = ErrStreamTimeout
resp.Close() // Closes the network connection to break blocking read
})
defer timer.Stop()
}
reader := bufio.NewReader(resp)
for {
select {
case <-r.Context().Done():
return r.Context().Err()
default:
}
line, err := reader.ReadString('\n')
if err != nil {
if timer != nil {
timer.Stop()
}
if timeoutErr != nil {
return timeoutErr
}
if err == io.EOF {
if line != "" {
if cbErr := callback(line); cbErr != nil {
return cbErr
}
}
break
}
return err
}
// Reset idle timeout timer on successful read
if timer != nil {
timer.Reset(r.idleTimeout)
}
if cbErr := callback(line); cbErr != nil {
return cbErr
}
}
return nil
}
// StreamSSE sets the "Accept: text/event-stream" header, executes the request,
// and parses the response stream adhering to the W3C Server-Sent Events specification.
// It invokes the callback only when a complete event block is dispatched (on double newline).
func (r *Request) StreamSSE(callback func(event Event) error) error {
r.Header("Accept", "text/event-stream")
resp, err := r.Stream()
if err != nil {
return err
}
defer resp.Close()
var timeoutErr error
var timer *time.Timer
if r.idleTimeout > 0 {
timer = time.AfterFunc(r.idleTimeout, func() {
timeoutErr = ErrStreamTimeout
resp.Close() // Closes the network connection to break blocking read
})
defer timer.Stop()
}
reader := bufio.NewReader(resp)
var currentEvent Event
var dataBuilder strings.Builder
hasData := false
for {
select {
case <-r.Context().Done():
return r.Context().Err()
default:
}
line, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
if timer != nil {
timer.Stop()
}
if timeoutErr != nil {
return timeoutErr
}
return err
}
// Reset idle timeout timer on successful read
if timer != nil {
timer.Reset(r.idleTimeout)
}
// Normalize line ending by stripping \r and \n
trimmedLine := strings.TrimRight(line, "\r\n")
if trimmedLine == "" {
// A blank line dispatches the currently accumulated event if we have active content
if hasData || currentEvent.Event != "" || currentEvent.ID != "" {
currentEvent.Data = dataBuilder.String()
if cbErr := callback(currentEvent); cbErr != nil {
return cbErr
}
// Reset event buffer
currentEvent = Event{}
dataBuilder.Reset()
hasData = false
}
if err == io.EOF {
break
}
continue
}
// Comments (lines starting with colon) are ignored
if strings.HasPrefix(trimmedLine, ":") {
if err == io.EOF {
break
}
continue
}
// Split line into field name and value
var field, value string
colonIdx := strings.Index(trimmedLine, ":")
if colonIdx == -1 {
field = trimmedLine
value = ""
} else {
field = trimmedLine[:colonIdx]
value = trimmedLine[colonIdx+1:]
// Strip leading space if present
if len(value) > 0 && value[0] == ' ' {
value = value[1:]
}
}
switch field {
case "event":
currentEvent.Event = value
case "data":
if hasData {
dataBuilder.WriteByte('\n')
}
dataBuilder.WriteString(value)
hasData = true
case "id":
currentEvent.ID = value
case "retry":
// We do not implement reconnection time changes, ignore
}
if err == io.EOF {
// Dispatch any remaining event on stream termination
if hasData || currentEvent.Event != "" || currentEvent.ID != "" {
currentEvent.Data = dataBuilder.String()
_ = callback(currentEvent)
}
break
}
}
return nil
}