James Tucker | 351df1b | 2018-11-05 14:35:17 -0800 | [diff] [blame] | 1 | // 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. |
| 12 | package sse |
| 13 | |
| 14 | import ( |
| 15 | "errors" |
| 16 | "net/http" |
| 17 | "strings" |
| 18 | ) |
| 19 | |
| 20 | // ErrNotAcceptable occurs when the incoming request does not Accept |
| 21 | // text/event-stream |
| 22 | var ErrNotAcceptable = errors.New("sse: invalid content-type") |
| 23 | var 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. |
| 32 | func 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. |
| 49 | func Write(w http.ResponseWriter, e *Event) error { |
| 50 | _, err := e.WriteTo(w) |
| 51 | w.(http.Flusher).Flush() |
| 52 | return err |
| 53 | } |