|
| 1 | +package httpresponse |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "sync" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +/////////////////////////////////////////////////////////////////////////////// |
| 14 | +// TYPES |
| 15 | + |
| 16 | +// TextStream implements a stream of text events |
| 17 | +type TextStream struct { |
| 18 | + wg sync.WaitGroup |
| 19 | + w io.Writer |
| 20 | + ch chan *textevent |
| 21 | + err error |
| 22 | +} |
| 23 | + |
| 24 | +type textevent struct { |
| 25 | + name string |
| 26 | + data []any |
| 27 | +} |
| 28 | + |
| 29 | +/////////////////////////////////////////////////////////////////////////////// |
| 30 | +// GLOBALS |
| 31 | + |
| 32 | +const ( |
| 33 | + defaultKeepAlive = 10 * time.Second |
| 34 | +) |
| 35 | + |
| 36 | +var ( |
| 37 | + strPing = "ping" |
| 38 | + strEvent = []byte("event: ") |
| 39 | + strData = []byte("data: ") |
| 40 | + strNewline = []byte("\n") |
| 41 | +) |
| 42 | + |
| 43 | +/////////////////////////////////////////////////////////////////////////////// |
| 44 | +// LIFECYCLE |
| 45 | + |
| 46 | +// Create a new text stream with mimetype text/event-stream |
| 47 | +// Additional header tuples can be provided as a series of key-value pairs |
| 48 | +func NewTextStream(w http.ResponseWriter, tuples ...string) *TextStream { |
| 49 | + // Check parameters |
| 50 | + if w == nil { |
| 51 | + return nil |
| 52 | + } |
| 53 | + if len(tuples)%2 != 0 { |
| 54 | + return nil |
| 55 | + } |
| 56 | + |
| 57 | + // Create a text stream |
| 58 | + self := new(TextStream) |
| 59 | + self.w = w |
| 60 | + self.ch = make(chan *textevent) |
| 61 | + |
| 62 | + // Set the default content type |
| 63 | + w.Header().Set(ContentTypeKey, ContentTypeTextStream) |
| 64 | + |
| 65 | + // Set additional headers |
| 66 | + for i := 0; i < len(tuples); i += 2 { |
| 67 | + w.Header().Set(tuples[i], tuples[i+1]) |
| 68 | + } |
| 69 | + |
| 70 | + // Write the response, don't know is this is the right one |
| 71 | + w.WriteHeader(http.StatusContinue) |
| 72 | + |
| 73 | + // goroutine will write to the response writer until the channel is closed |
| 74 | + self.wg.Add(1) |
| 75 | + go func() { |
| 76 | + defer self.wg.Done() |
| 77 | + |
| 78 | + // Create a ticker for ping messages |
| 79 | + ticker := time.NewTimer(100 * time.Millisecond) |
| 80 | + defer ticker.Stop() |
| 81 | + |
| 82 | + // Run until the channel is closed |
| 83 | + for { |
| 84 | + select { |
| 85 | + case evt := <-self.ch: |
| 86 | + if evt == nil { |
| 87 | + return |
| 88 | + } |
| 89 | + self.emit(evt) |
| 90 | + case <-ticker.C: |
| 91 | + self.err = errors.Join(self.err, self.emit(&textevent{strPing, nil})) |
| 92 | + ticker.Reset(defaultKeepAlive) |
| 93 | + } |
| 94 | + } |
| 95 | + }() |
| 96 | + |
| 97 | + // Return the textstream object |
| 98 | + return self |
| 99 | +} |
| 100 | + |
| 101 | +// Close the text stream to stop sending ping messages |
| 102 | +func (s *TextStream) Close() error { |
| 103 | + // Close the channel |
| 104 | + close(s.ch) |
| 105 | + |
| 106 | + // Wait for the goroutine to finish |
| 107 | + s.wg.Wait() |
| 108 | + |
| 109 | + // Return any errors |
| 110 | + return s.err |
| 111 | +} |
| 112 | + |
| 113 | +/////////////////////////////////////////////////////////////////////////////// |
| 114 | +// PUBLIC METHODS |
| 115 | + |
| 116 | +// Write a text event to the stream, and one or more optional data objects |
| 117 | +// which are encoded as JSON |
| 118 | +func (s *TextStream) Write(name string, data ...any) { |
| 119 | + s.ch <- &textevent{name, data} |
| 120 | +} |
| 121 | + |
| 122 | +/////////////////////////////////////////////////////////////////////////////// |
| 123 | +// PRIVATE METHODS |
| 124 | + |
| 125 | +// emit an event to the stream |
| 126 | +func (s *TextStream) emit(e *textevent) error { |
| 127 | + var result error |
| 128 | + |
| 129 | + // Write the event to the stream |
| 130 | + if e.name != "" { |
| 131 | + if err := s.write(strEvent, []byte(e.name), strNewline); err != nil { |
| 132 | + return err |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + // Write the data to the stream |
| 137 | + for _, v := range e.data { |
| 138 | + if v == nil { |
| 139 | + continue |
| 140 | + } else if data, err := json.Marshal(v); err != nil { |
| 141 | + result = errors.Join(result, err) |
| 142 | + } else if err := s.write(strData, data, strNewline); err != nil { |
| 143 | + result = errors.Join(result, err) |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + // Flush the event |
| 148 | + if result == nil { |
| 149 | + if err := s.write(strNewline); err != nil { |
| 150 | + result = errors.Join(result, err) |
| 151 | + } |
| 152 | + if w, ok := s.w.(http.Flusher); ok { |
| 153 | + w.Flush() |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + // Return any errors |
| 158 | + return result |
| 159 | +} |
| 160 | + |
| 161 | +func (s *TextStream) write(v ...[]byte) error { |
| 162 | + if _, err := s.w.Write(bytes.Join(v, nil)); err != nil { |
| 163 | + return err |
| 164 | + } |
| 165 | + return nil |
| 166 | +} |
0 commit comments