Skip to content

Commit 5e66ec2

Browse files
committed
make client more configurable
1 parent 48c1157 commit 5e66ec2

File tree

1 file changed

+37
-12
lines changed

1 file changed

+37
-12
lines changed

client.go

+37-12
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package eventsource
33
import (
44
"context"
55
"io"
6+
"log"
67
"net/http"
78
"sync"
89
"time"
@@ -11,14 +12,20 @@ import (
1112
// Client wraps an http connection and converts it to an
1213
// event stream.
1314
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
2229
}
2330

2431
// NewClient creates a client wrapping a response writer.
@@ -27,10 +34,28 @@ type Client struct {
2734
// original http.Request helps determine which headers, but the request it is
2835
// optional.
2936
// 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+
3155
c := &Client{
32-
events: make(chan Event, 100),
33-
write: w,
56+
events: make(chan Event, channelSize),
57+
write: w,
58+
flushLatency: flushLatency,
3459
}
3560

3661
// Check to ensure we support flushing
@@ -122,7 +147,7 @@ func (c *Client) run() {
122147
c.lock.Lock()
123148
io.Copy(c.write, &ev)
124149
if c.flushing == nil {
125-
c.flushing = time.AfterFunc(100*time.Millisecond, c.flush)
150+
c.flushing = time.AfterFunc(c.flushLatency, c.flush)
126151
}
127152
c.lock.Unlock()
128153

0 commit comments

Comments
 (0)