feat: SSE handler, send y keepalive (issue 0011 fase 2)
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SSEKeepalive envia comentarios SSE periodicos (": keepalive\n\n") al writer
|
||||
// hasta que done se cierre. Bloqueante: lanzar como goroutine.
|
||||
// Sirve para evitar que proxies/load balancers cierren conexiones inactivas.
|
||||
// Si w implementa http.Flusher hace flush tras cada keepalive.
|
||||
func SSEKeepalive(w http.ResponseWriter, interval time.Duration, done <-chan struct{}) {
|
||||
if interval <= 0 {
|
||||
interval = 30 * time.Second
|
||||
}
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
flusher, _ := w.(http.Flusher)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-ticker.C:
|
||||
if _, err := w.Write([]byte(": keepalive\n\n")); err != nil {
|
||||
return
|
||||
}
|
||||
if flusher != nil {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user