summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2023-11-27 19:04:56 +0700
committerShulhan <ms@kilabit.info>2023-11-27 19:04:56 +0700
commit635cdf86fcfdef46f708c32467a5bd578a96baf7 (patch)
treec3bdf27d611bae7d50b577a4fe7694cffd49e604
parent5b7f3a702aa8210e9f3efcc9befeceb87755fc4d (diff)
downloadpakakeh.go-635cdf86fcfdef46f708c32467a5bd578a96baf7.tar.xz
lib/http: add field KeepAliveInterval in SSEEndpoint
The KeepAliveInterval define the interval where server will send a an empty message ":\n\n" to active connection periodically. This field is optional, default and minimum value is 5 seconds.
-rw-r--r--lib/http/sse_conn.go20
-rw-r--r--lib/http/sse_endpoint.go12
2 files changed, 32 insertions, 0 deletions
diff --git a/lib/http/sse_conn.go b/lib/http/sse_conn.go
index 66e47c94..a39b7817 100644
--- a/lib/http/sse_conn.go
+++ b/lib/http/sse_conn.go
@@ -93,6 +93,26 @@ func (ep *SSEConn) WriteRetry(retry time.Duration) (err error) {
return nil
}
+// workerKeepAlive periodically send an empty message to client to keep the
+// connection alive.
+func (ep *SSEConn) workerKeepAlive(interval time.Duration) {
+ var (
+ ticker = time.NewTicker(interval)
+ emptyMsg = []byte(":\n\n")
+
+ err error
+ )
+ for _ = range ticker.C {
+ err = ep.WriteRaw(emptyMsg)
+ if err != nil {
+ // Write failed, probably connection has been
+ // closed.
+ ticker.Stop()
+ return
+ }
+ }
+}
+
func (ep *SSEConn) writeData(buf *bytes.Buffer, data string, id *string) {
var (
lines = strings.Split(data, "\n")
diff --git a/lib/http/sse_endpoint.go b/lib/http/sse_endpoint.go
index b6804d8d..20918d54 100644
--- a/lib/http/sse_endpoint.go
+++ b/lib/http/sse_endpoint.go
@@ -8,10 +8,13 @@ import (
"errors"
"net/http"
"net/url"
+ "time"
liberrors "github.com/shuLhan/share/lib/errors"
)
+const defKeepAliveInterval = 5 * time.Second
+
// SSEEndpoint endpoint to create Server-Sent Events (SSE) on server.
//
// For creating the SSE client see subpackage [sseclient].
@@ -21,6 +24,11 @@ type SSEEndpoint struct {
// Path where server accept the request for SSE.
Path string
+
+ // KeepAliveInterval define the interval where server will send an
+ // empty message to active connection periodically.
+ // This field is optional, default and minimum value is 5 seconds.
+ KeepAliveInterval time.Duration
}
func (ep *SSEEndpoint) call(
@@ -64,6 +72,10 @@ func (ep *SSEEndpoint) call(
}
sseconn.handshake()
+ if ep.KeepAliveInterval < defKeepAliveInterval {
+ ep.KeepAliveInterval = defKeepAliveInterval
+ }
+ go sseconn.workerKeepAlive(ep.KeepAliveInterval)
ep.Call(sseconn)
sseconn.conn.Close()
}