35 lines
765 B
Go
35 lines
765 B
Go
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()
|
|
}
|
|
}
|
|
}
|
|
}
|