#Passing Channel to Echo Handler

7 messages · Page 1 of 1 (latest)

zinc dove
#

What would be a good way to pass a channel to an Echo/http handler? I've created a custom context to pass database access to them, but I can't work out in my mind how I would do any communication to/from them

The point would be for Server Sent Events -- I'm trying to make a basic notification demo and I'm not really sure how I could send an event from one client to the other,

func sse(c echo.Context) error {
    header := c.Response().Header()
    header.Set("Access-Control-Allow-Origin", "*")
    header.Set("Access-Control-Expose-Headers", "Content-Type")
    header.Set("Content-Type", "text/event-stream")
    header.Set("Cache-Control", "no-cache")
    header.Set("Connection", "keep-alive")
    users_connected += 1
    for {
        // need channel here
        _, err := fmt.Fprintf(c.Response().Writer, "data: %s\n\n",
            fmt.Sprintf("Users Connected: %d", users_connected))
        if err != nil {
            c.Logger().Error(err)
            break
        }
        c.Response().Flush()
        time.Sleep(time.Second)
    }
    users_connected -= 1
    return nil
}
#

this is isolated from the script with the custom context, i should mention -- if that's a way to do it then that would be good

placid lagoon
#

How about something like:

func sseHandler(ch chan something) echo.HandlerFunc {
  return func(c echo.Context) error {
      header := c.Response().Header()
      header.Set("Access-Control-Allow-Origin", "*")
      header.Set("Access-Control-Expose-Headers", "Content-Type")
      header.Set("Content-Type", "text/event-stream")
      header.Set("Cache-Control", "no-cache")
      header.Set("Connection", "keep-alive")
      users_connected += 1
      for {
          // need channel here
          _, err := fmt.Fprintf(c.Response().Writer, "data: %s\n\n",
              fmt.Sprintf("Users Connected: %d", users_connected))
          if err != nil {
              c.Logger().Error(err)
              break
          }
          c.Response().Flush()
          time.Sleep(time.Second)
      }
      users_connected -= 1
      return nil
  }
  }
#

use it sort of like this:

e.GET("/events", sseHandler(ch))
zinc dove
#

that seems like the business to me

#

I'll give it a go, thanks!

placid lagoon
#

hope it works out, good luck