Created
April 6, 2016 19:48
-
-
Save sdorra/f7de3cbfb884f6ff0c9f0c4ec7cf4046 to your computer and use it in GitHub Desktop.
SSEvents with golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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