@@ -3,6 +3,7 @@ package eventsource
3
3
import (
4
4
"context"
5
5
"io"
6
+ "log"
6
7
"net/http"
7
8
"sync"
8
9
"time"
@@ -11,14 +12,20 @@ import (
11
12
// Client wraps an http connection and converts it to an
12
13
// event stream.
13
14
type Client struct {
14
- flusher http.Flusher
15
- write io.Writer
16
- ctx context.Context
17
- events chan Event
18
- closed bool
19
- waiter sync.WaitGroup
20
- lock sync.Mutex
21
- flushing * time.Timer
15
+ flusher http.Flusher
16
+ write io.Writer
17
+ ctx context.Context
18
+ events chan Event
19
+ closed bool
20
+ waiter sync.WaitGroup
21
+ lock sync.Mutex
22
+ flushing * time.Timer
23
+ flushLatency time.Duration
24
+ }
25
+
26
+ type Options struct {
27
+ ChannelSize int
28
+ FlushLatency time.Duration
22
29
}
23
30
24
31
// NewClient creates a client wrapping a response writer.
@@ -27,10 +34,28 @@ type Client struct {
27
34
// original http.Request helps determine which headers, but the request it is
28
35
// optional.
29
36
// Returns nil on error.
30
- func NewClient (w http.ResponseWriter , req * http.Request ) * Client {
37
+ func NewClient (w http.ResponseWriter , req * http.Request , options ... Options ) * Client {
38
+ if len (options ) > 1 {
39
+ log .Panicln ("only one Options value may be provided" )
40
+ }
41
+
42
+ flushLatency := 100 * time .Millisecond
43
+ channelSize := 100
44
+
45
+ if len (options ) == 1 {
46
+ options := options [0 ]
47
+ if options .FlushLatency > 0 {
48
+ flushLatency = options .FlushLatency
49
+ }
50
+ if options .ChannelSize > 0 {
51
+ channelSize = options .ChannelSize
52
+ }
53
+ }
54
+
31
55
c := & Client {
32
- events : make (chan Event , 100 ),
33
- write : w ,
56
+ events : make (chan Event , channelSize ),
57
+ write : w ,
58
+ flushLatency : flushLatency ,
34
59
}
35
60
36
61
// Check to ensure we support flushing
@@ -122,7 +147,7 @@ func (c *Client) run() {
122
147
c .lock .Lock ()
123
148
io .Copy (c .write , & ev )
124
149
if c .flushing == nil {
125
- c .flushing = time .AfterFunc (100 * time . Millisecond , c .flush )
150
+ c .flushing = time .AfterFunc (c . flushLatency , c .flush )
126
151
}
127
152
c .lock .Unlock ()
128
153
0 commit comments