handleEvents handles the "GET /events" route. This route provides real-time event notification over Websockets.
(w http.ResponseWriter, r *http.Request)
| 27 | // handleEvents handles the "GET /events" route. This route provides real-time |
| 28 | // event notification over Websockets. |
| 29 | func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) { |
| 30 | websocketConnections.Inc() |
| 31 | defer websocketConnections.Dec() |
| 32 | |
| 33 | // Upgrade HTTP connection to use websockets. |
| 34 | conn, err := upgrader.Upgrade(w, r, nil) |
| 35 | if err != nil { |
| 36 | LogError(r, err) |
| 37 | return |
| 38 | } |
| 39 | |
| 40 | ctx, cancel := context.WithCancel(r.Context()) |
| 41 | r = r.WithContext(ctx) |
| 42 | conn.SetCloseHandler(func(code int, text string) error { |
| 43 | cancel() |
| 44 | return nil |
| 45 | }) |
| 46 | |
| 47 | // We defer the connection close to ensure it is disconnected when we |
| 48 | // exit this function. This can occur if the HTTP request disconnects or |
| 49 | // if the subscription from the event service closes. |
| 50 | defer conn.Close() |
| 51 | |
| 52 | // Ignore all incoming messages. |
| 53 | go ignoreWebSocketReaders(conn) |
| 54 | |
| 55 | // Subscribe to all events for the current user. |
| 56 | sub, err := s.EventService.Subscribe(r.Context()) |
| 57 | if err != nil { |
| 58 | LogError(r, err) |
| 59 | return |
| 60 | } |
| 61 | defer sub.Close() |
| 62 | |
| 63 | // Stream all events to outgoing websocket writer. |
| 64 | for { |
| 65 | select { |
| 66 | case <-r.Context().Done(): |
| 67 | return // disconnect when HTTP connection disconnects |
| 68 | |
| 69 | case event, ok := <-sub.C(): |
| 70 | // If subscription is closed then exit. |
| 71 | if !ok { |
| 72 | return |
| 73 | } |
| 74 | |
| 75 | // Marshal event data to JSON. |
| 76 | buf, err := json.Marshal(event) |
| 77 | if err != nil { |
| 78 | LogError(r, err) |
| 79 | return |
| 80 | } |
| 81 | |
| 82 | // Write JSON data out to the websocket connection. |
| 83 | if err := conn.WriteMessage(websocket.TextMessage, buf); err != nil { |
| 84 | LogError(r, err) |
| 85 | return |
| 86 | } |
nothing calls this directly
no test coverage detected