Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eventsource golang : how to detect client disconnection?

I'm developing chat rooms based on Twitter hashtag with Server sent events, with the package https://github.com/antage/eventsource

I have a problem concerning the disconnection of the client. I run a goroutine to send messages to the client, but when the client disconnects, the goroutine still runs.

I don't know how to detect on the server side that the client is disconnected.

func (sh StreamHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {

    es := eventsource.New(
        &eventsource.Settings{
            Timeout:        2 * time.Second,
            CloseOnTimeout: true,
            IdleTimeout:    2 * time.Second,
            Gzip:           true,
        },
        func(req *http.Request) [][]byte {
            return [][]byte{
                []byte("X-Accel-Buffering: no"),
                []byte("Access-Control-Allow-Origin: *"),
            }
        },
    )

    es.ServeHTTP(resp, req)

    go func() {
        var id int
        for {
            id++
            time.Sleep(1 * time.Second)
            es.SendEventMessage("blabla", "message", strconv.Itoa(id))
        }
    }()

}
like image 227
GuillaumeP Avatar asked Aug 20 '15 16:08

GuillaumeP


2 Answers

As of December 2018, apparently CloseNotifier is deprecated. The recommended solution is to use the Request Context. The following worked for me:

done := make(chan bool)
go func() {
        <-req.Context().Done()
        done <- true
}()
<-done
like image 166
anderspitman Avatar answered Oct 20 '22 21:10

anderspitman


You can use CloseNotifier which lets you know if the underlying http connection has closed. Like:

notify := w.(http.CloseNotifier).CloseNotify()
go func() {
    <-notify
    // connection close, do cleanup, etc.
}()

HTH

like image 26
Marconi Avatar answered Oct 20 '22 23:10

Marconi