Skip to content

Commit 06583f8

Browse files
committed
Add a http.Request parameter to NewClient()
Use the request to determine whether to send Connection: keep-alive — it's not necessary for HTTP/2 connections. Signed-off-by: Tim Ekl <[email protected]>
1 parent 8d57873 commit 06583f8

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

client.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,11 @@ type Client struct {
2020
// NewClient creates a client wrapping a response writer.
2121
// The response writer must support http.Flusher and http.CloseNotifier
2222
// interfaces.
23+
// When writing, the client will automatically send some headers. Passing the
24+
// original http.Request helps determine which headers, but the request it is
25+
// optional.
2326
// Returns nil on error.
24-
func NewClient(w http.ResponseWriter) *Client {
27+
func NewClient(w http.ResponseWriter, req *http.Request) *Client {
2528
c := &Client{
2629
events: make(chan *Event, 1),
2730
write: w,
@@ -44,7 +47,9 @@ func NewClient(w http.ResponseWriter) *Client {
4447
// Send the initial headers
4548
w.Header().Set("Content-Type", "text/event-stream")
4649
w.Header().Set("Cache-Control", "no-cache")
47-
w.Header().Set("Connection", "keep-alive")
50+
if req == nil || req.ProtoMajor < 2 {
51+
w.Header().Set("Connection", "keep-alive")
52+
}
4853
flush.Flush()
4954

5055
// start the sending thread

stream.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ func (s *Stream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
161161
}
162162

163163
// create the client
164-
c := NewClient(w)
164+
c := NewClient(w, r)
165165
if c == nil {
166166
http.Error(w, "EventStream not supported for this connection", http.StatusInternalServerError)
167167
return
@@ -188,7 +188,7 @@ func (s *Stream) TopicHandler(topics []string) http.HandlerFunc {
188188
}
189189

190190
// create the client
191-
c := NewClient(w)
191+
c := NewClient(w, r)
192192
if c == nil {
193193
http.Error(w, "EventStream not supported for this connection", http.StatusInternalServerError)
194194
return

0 commit comments

Comments
 (0)