Skip to content

Commit f938a8c

Browse files
committed
fix SSE example disconnecting after 30 sec by disabling write timeout as this connection is long-lived
1 parent 583680b commit f938a8c

2 files changed

Lines changed: 36 additions & 7 deletions

File tree

cookbook/sse/broadcast/server.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package main
22

33
import (
4-
"errors"
4+
"context"
55
"net/http"
6+
"os"
7+
"os/signal"
8+
"syscall"
69
"time"
710

811
"github.com/labstack/echo/v5"
@@ -49,7 +52,17 @@ func main() {
4952
return nil
5053
})
5154

52-
if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) {
53-
e.Logger.Error("shutting down the server", "error", err)
55+
sc := echo.StartConfig{
56+
Address: ":8080",
57+
BeforeServeFunc: func(s *http.Server) error {
58+
s.WriteTimeout = 0 // IMPORTANT: disable for SSE
59+
return nil
60+
},
61+
}
62+
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) // start shutdown process on ctrl+c
63+
defer cancel()
64+
65+
if err := sc.Start(ctx, e); err != nil {
66+
e.Logger.Error("failed to start server", "error", err)
5467
}
5568
}

cookbook/sse/simple/server.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
package main
22

33
import (
4-
"errors"
4+
"context"
5+
"fmt"
56
"log"
67
"net/http"
8+
"os"
9+
"os/signal"
10+
"syscall"
711
"time"
812

913
"github.com/labstack/echo/v5"
@@ -27,14 +31,16 @@ func main() {
2731

2832
ticker := time.NewTicker(1 * time.Second)
2933
defer ticker.Stop()
34+
count := uint64(0)
3035
for {
3136
select {
3237
case <-c.Request().Context().Done():
3338
log.Printf("SSE client disconnected, ip: %v", c.RealIP())
3439
return nil
3540
case <-ticker.C:
41+
count++
3642
event := Event{
37-
Data: []byte("time: " + time.Now().Format(time.RFC3339Nano)),
43+
Data: []byte(fmt.Sprintf("count: %d, time: %s\n\n", count, time.Now().Format(time.RFC3339Nano))),
3844
}
3945
if err := event.MarshalTo(w); err != nil {
4046
return err
@@ -46,7 +52,17 @@ func main() {
4652
}
4753
})
4854

49-
if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) {
50-
log.Fatal(err)
55+
sc := echo.StartConfig{
56+
Address: ":8080",
57+
BeforeServeFunc: func(s *http.Server) error {
58+
s.WriteTimeout = 0 // IMPORTANT: disable for SSE
59+
return nil
60+
},
61+
}
62+
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) // start shutdown process on ctrl+c
63+
defer cancel()
64+
65+
if err := sc.Start(ctx, e); err != nil {
66+
e.Logger.Error("failed to start server", "error", err)
5167
}
5268
}

0 commit comments

Comments
 (0)