Skip to content

Commit 4f4191e

Browse files
authored
perf: allocate header values only one time (#1120)
* perf: allocate header values only one time * fix canocalization
1 parent 769d065 commit 4f4191e

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

subscribe.go

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -237,24 +237,36 @@ func (h *Hub) registerSubscriber(ctx context.Context, w http.ResponseWriter, r *
237237
return s, rc
238238
}
239239

240+
//nolint:gochecknoglobals
241+
var (
242+
headerConnection = []string{"keep-alive"}
243+
headerContentType = []string{"text/event-stream"}
244+
headerCacheControl = []string{"private, no-cache, no-store, must-revalidate, max-age=0"}
245+
headerPragma = []string{"no-cache"}
246+
headerExpire = []string{"0"}
247+
248+
headerXAccelBuffering = []string{"no"}
249+
)
250+
240251
// sendHeaders sends correct HTTP headers to create a keep-alive connection.
241252
func (h *Hub) sendHeaders(ctx context.Context, w http.ResponseWriter, s *LocalSubscriber) {
253+
header := w.Header()
254+
242255
// Keep alive, useful only for HTTP 1 clients https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive
243-
w.Header().Set("Connection", "keep-alive")
256+
header["Connection"] = headerConnection
244257

245-
// Server-sent events https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Sending_events_from_the_server
246-
w.Header().Set("Content-Type", "text/event-stream")
258+
header["Content-Type"] = headerContentType
247259

248260
// Disable cache, even for old browsers and proxies
249-
w.Header().Set("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0")
250-
w.Header().Set("Pragma", "no-cache")
251-
w.Header().Set("Expire", "0")
261+
header["Cache-Control"] = headerCacheControl
262+
header["Pragma"] = headerPragma
263+
header["Expire"] = headerExpire
252264

253265
// NGINX support https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-buffering
254-
w.Header().Set("X-Accel-Buffering", "no")
266+
header["X-Accel-Buffering"] = headerXAccelBuffering
255267

256268
if s.RequestLastEventID != "" {
257-
w.Header().Set("Last-Event-ID", <-s.responseLastEventID)
269+
header["Last-Event-Id"] = []string{<-s.responseLastEventID}
258270
}
259271

260272
// Write a comment in the body

0 commit comments

Comments
 (0)