Are Server Sent Events supported? If yes, is there an example I can follow?
Sure, here is a simple self explanatory example:
package main
import (
"bufio"
"bytes"
"fmt"
"time"
"github.com/valyala/fasthttp"
)
func handler(ctx *fasthttp.RequestCtx) {
if bytes.HasPrefix(ctx.Path(), []byte("/source")) {
ctx.SetContentType("text/event-stream")
ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
for {
w.Write([]byte(fmt.Sprintf("data: %s\n\n", time.Now())))
w.Flush()
time.Sleep(time.Second)
}
})
} else {
ctx.SetContentType("text/html")
ctx.SetBody([]byte(`
<!doctype html>
<body>
<div id=d></div>
<script>
var source = new EventSource('http://localhost:8080/source');
source.onmessage = function(e) {
document.getElementById('d').innerHTML = e.data;
};
</script>
`))
}
}
func main() {
if err := fasthttp.ListenAndServe(":8080", handler); err != nil {
panic(err)
}
}
Thanks a lot
Hi, I am trying to use your example in my application, but it looks like in case a client closes connection, a go routine processing SSE still runs, causing a memory leak. Is there any way to handle that correctly? Thank you!
That's because fasthttp uses a worker pool. So the next time a client connects it will reuse the goroutine. So this is not really a memory leak and the overhead of one goroutine is very small.
Most helpful comment
Sure, here is a simple self explanatory example: