Fasthttp: Server Sent Events

Created on 18 Sep 2018  路  4Comments  路  Source: valyala/fasthttp

Are Server Sent Events supported? If yes, is there an example I can follow?

question

Most helpful comment

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)
  }
}

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

imgurbot12 picture imgurbot12  路  5Comments

Fenny picture Fenny  路  4Comments

horgh picture horgh  路  5Comments

kirillDanshin picture kirillDanshin  路  5Comments

iowelinux picture iowelinux  路  3Comments