Skip to content

Instantly share code, notes, and snippets.

@sdorra
Created April 6, 2016 19:48
Show Gist options
  • Save sdorra/f7de3cbfb884f6ff0c9f0c4ec7cf4046 to your computer and use it in GitHub Desktop.
Save sdorra/f7de3cbfb884f6ff0c9f0c4ec7cf4046 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment