Skip to content

Instantly share code, notes, and snippets.

@alexyslozada
Created September 21, 2021 14:17
Show Gist options
  • Save alexyslozada/2909920a0c8c904cb9e38c0c6724849e to your computer and use it in GitHub Desktop.
Save alexyslozada/2909920a0c8c904cb9e38c0c6724849e to your computer and use it in GitHub Desktop.
How to create a handler to SSE
func (h *Handler) Subscribe(c echo.Context) error {
var epoch = time.Unix(0, 0).Format(time.RFC1123)
c.Response().Header().Set(echo.HeaderContentType, "text/event-stream")
c.Response().Header().Set("Cache-Control", "no-cache")
c.Response().Header().Set("Connection", "keep-alive")
c.Response().Header().Set("Expires", epoch)
c.Response().Header().Set("Cache-Control", "no-cache, private, max-age=0")
c.Response().Header().Set("Pragma", "no-cache")
c.Response().Header().Set("X-Accel-Expires", "0")
c.Response().WriteHeader(http.StatusOK)
// knowWhenCloseConnectionClient is a listener to know when the user close the connection. e.g. close browser.
knowWhenCloseConnectionClient := c.Request().Context().Done()
client := h.sse.Subscribe(knowWhenCloseConnectionClient)
defer h.sse.UnSubscribe(client)
for {
message := <-client.QueueMessages
dataJSON, err := json.Marshal(message)
if err != nil {
log.Printf("Can't marshal message %v, error was %v", message, err)
return c.JSON(http.StatusInternalServerError, err)
}
// Send message to client
_, err = fmt.Fprintf(c.Response(), "data: %v\n\n", string(dataJSON))
if err != nil {
return err
}
c.Response().Flush()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment