Skip to content

Instantly share code, notes, and snippets.

@walm
Forked from sdorra/app.go
Created December 4, 2019 19:43
Show Gist options
  • Save walm/6ea598f693ac76963b8784093b6e824a to your computer and use it in GitHub Desktop.
Save walm/6ea598f693ac76963b8784093b6e824a to your computer and use it in GitHub Desktop.
SSEvents with golang
package main
import (
"io"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
// Event for SSE
type Event struct {
ID int
Message string
}
func sendEvents(listener chan interface{}) {
i := 0
ticker := time.NewTicker(1 * time.Second)
for _ = range ticker.C {
i++
listener <- Event{i, "Hello " + strconv.Itoa(i)}
if i >= 5 {
ticker.Stop()
close(listener)
}
}
}
func streamEvents(c *gin.Context) {
listener := make(chan interface{})
go sendEvents(listener)
c.Stream(func(w io.Writer) bool {
event := <-listener
if event != nil {
c.SSEvent("message", event)
return true
}
return false
})
}
func ping(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
}
func main() {
r := gin.Default()
r.GET("/ping", ping)
r.GET("/stream", streamEvents)
r.Run() // listen and server on 0.0.0.0:8080
}
var client = new EventSource("http://localhost:8080/stream/")
client.onmessage = function (msg) {
console.log(msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment