blob: 53766de3533c8f0c4b090f4ba7dc384938cf7d61 [file] [log] [blame]
James Tucker351df1b2018-11-05 14:35:17 -08001// Copyright 2018 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Package sse provides support for Server-Sent Events, as a handler for
6// net/http, and a client that can read SSE events from net/http responses.
7//
8// SSE is specified here: http://www.w3.org/TR/eventsource/
9//
10// The package implements only partial support for SSE, specifically the client
11// and server do not handle retries or event buffering.
12package sse
13
14import (
15 "errors"
16 "net/http"
17 "strings"
18)
19
20// ErrNotAcceptable occurs when the incoming request does not Accept
21// text/event-stream
22var ErrNotAcceptable = errors.New("sse: invalid content-type")
23var headers = map[string]string{
24 "Content-Type": "text/event-stream",
25 "Cache-Control": "no-cache",
26 "X-Accel-Buffering": "no",
27}
28
29// Start asserts that the client wants SSE, and if so, begins writing an SSE
30// stream with the appropriate response headers. It performs a forced flush on
31// the stream to ensure that the client receives the headers immediately.
32func Start(w http.ResponseWriter, r *http.Request) error {
33 if !strings.Contains(r.Header.Get("Accept"), "text/event-stream") {
34 return ErrNotAcceptable
35 }
36
37 for h, v := range headers {
38 w.Header().Set(h, v)
39 }
40
41 w.WriteHeader(200)
42
43 w.(http.Flusher).Flush()
44
45 return nil
46}
47
48// Write sends an event to an http ResponseWriter, flushing afterward.
49func Write(w http.ResponseWriter, e *Event) error {
50 _, err := e.WriteTo(w)
51 w.(http.Flusher).Flush()
52 return err
53}