-
-
Save walm/6ea598f693ac76963b8784093b6e824a to your computer and use it in GitHub Desktop.
SSEvents with golang
This file contains hidden or 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 | |
} |
This file contains hidden or 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
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