1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| package main
import ( "net/http" )
type SSE struct { writer http.ResponseWriter flusher http.Flusher sendCh chan []byte closeCh chan bool }
func NewSSE(w http.ResponseWriter) *SSE { setHttpHeader(w) return &SSE{ writer: w, flusher: w.(http.Flusher), sendCh: make(chan []byte), closeCh: make(chan bool), } }
func setHttpHeader(w http.ResponseWriter) { w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") w.Header().Set("Access-Control-Allow-Origin", "*") }
func (s *SSE) Run() { for { select { case msg := <-s.sendCh: s.send(msg) case <-s.closeCh: return } } }
func (s *SSE) send(msg []byte) { if _, err := s.writer.Write(msg); err != nil { return } s.flusher.Flush() }
func (s *SSE) Send(data []byte) { s.sendCh <- data }
func (s *SSE) Close() { s.closeCh <- true }
|