GetSessionWS upgrades to WebSocket and streams command results for a session.
(c *gin.Context)
| 128 | |
| 129 | // GetSessionWS upgrades to WebSocket and streams command results for a session. |
| 130 | func (h *Handler) GetSessionWS(c *gin.Context) { |
| 131 | id := c.Param("id") |
| 132 | sess := sessions.Global().Get(id) |
| 133 | if sess == nil { |
| 134 | c.JSON(404, gin.H{"error": "session not found"}) |
| 135 | return |
| 136 | } |
| 137 | |
| 138 | conn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil) |
| 139 | if err != nil { |
| 140 | return |
| 141 | } |
| 142 | defer conn.Close() |
| 143 | |
| 144 | subID := sessions.GenerateCommandID() // reuse as unique sub ID |
| 145 | ch := sessions.Global().Subscribe(id, subID) |
| 146 | if ch == nil { |
| 147 | return |
| 148 | } |
| 149 | defer sessions.Global().Unsubscribe(id, subID) |
| 150 | |
| 151 | // Read goroutine to detect client disconnect. |
| 152 | done := make(chan struct{}) |
| 153 | go func() { |
| 154 | defer close(done) |
| 155 | for { |
| 156 | if _, _, err := conn.ReadMessage(); err != nil { |
| 157 | return |
| 158 | } |
| 159 | } |
| 160 | }() |
| 161 | |
| 162 | for { |
| 163 | select { |
| 164 | case result, ok := <-ch: |
| 165 | if !ok { |
| 166 | return |
| 167 | } |
| 168 | if err := conn.WriteJSON(result); err != nil { |
| 169 | return |
| 170 | } |
| 171 | case <-done: |
| 172 | return |
| 173 | } |
| 174 | } |
| 175 | } |
nothing calls this directly
no test coverage detected