#1707727407
[ golang | webdev ]
SSE are cool.
This an example using the Echo framework in Golang. It sets up the connection, consumes a channel and sends that data to the user. It also exits the loop if the connection is broken, this is communicated via the request context.
func BuildingSSE(c echo.Context) error {
c.Response().Header().Set(echo.HeaderCacheControl, "no-cache")
c.Response().Header().Set(echo.HeaderConnection, "keep-alive")
c.Response().Header().Set(echo.HeaderContentType, "text/event-stream")
queue := queue.GetBuildQueue()
ctx := c.Request().Context()
for {
select {
case result := <-queue.BuildLogsChannel:
fmt.Fprint(c.Response(), buildSSE("message", result))
c.Response().Flush()
case <-ctx.Done():
return nil
}
}
}
func buildSSE(event, context string) string {
var result string
if len(event) != 0 {
result = result + "event: " + event + "\n"
}
if len(context) != 0 {
result = result + "data: " + context + "\n"
}
result = result + "\n"
return result
}