-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstream_reader.go
86 lines (75 loc) · 1.65 KB
/
stream_reader.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
package coze
import (
"bufio"
"context"
"io"
"net/http"
"strings"
)
type streamable interface {
ChatEvent | WorkflowEvent
}
type Stream[T streamable] interface {
Responser
Close() error
Recv() (*T, error)
}
type eventProcessor[T streamable] func(line []byte, reader *bufio.Reader) (*T, bool, error)
type streamReader[T streamable] struct {
isFinished bool
ctx context.Context
reader *bufio.Reader
response *http.Response
processor eventProcessor[T]
httpResponse *httpResponse
}
func (s *streamReader[T]) Recv() (response *T, err error) {
return s.processLines()
}
func (s *streamReader[T]) processLines() (*T, error) {
err := s.checkRespErr()
if err != nil {
return nil, err
}
for {
line, _, readErr := s.reader.ReadLine()
if readErr != nil {
return nil, readErr
}
if line == nil {
s.isFinished = true
break
}
if len(line) == 0 {
continue
}
event, isDone, err := s.processor(line, s.reader)
if err != nil {
return nil, err
}
s.isFinished = isDone
if event == nil {
continue
}
return event, nil
}
return nil, io.EOF
}
func (s *streamReader[T]) checkRespErr() error {
contentType := s.response.Header.Get("Content-Type")
if contentType != "" && strings.Contains(contentType, "application/json") {
respStr, err := io.ReadAll(s.response.Body)
if err != nil {
logger.Warnf(s.ctx, "Error reading response body: ", err)
return err
}
return isResponseSuccess(s.ctx, &baseResponse{}, respStr, s.httpResponse)
}
return nil
}
func (s *streamReader[T]) Close() error {
return s.response.Body.Close()
}
func (s *streamReader[T]) Response() HTTPResponse {
return s.httpResponse
}