Package sse is a middleware that provides Server-Sent Events for Flamego.
go get github.com/flamego/sse
<!-- templates/index.html --> <script src="https://cdn.jsdelivr.net/npm/way-js@0.2.1/dist/way.js"></script> <p><b><span way-data="data"></span></b>[<span way-data="published-at"></span>]</p> <script> let es = new EventSource("/bulletin"); es.onmessage = (evt) => { let bulletin = JSON.parse(evt.data); way.set('data', bulletin.Data) way.set('published-at', new Date(bulletin.PublishedAt).toLocaleString()) }; </script>
package main import ( "math/rand" "net/http" "time" "github.com/flamego/flamego" "github.com/flamego/sse" "github.com/flamego/template" ) var bulletins = []string{"Hello Flamego!", "Flamingo? No, Flamego!", "Most powerful routing syntax", "Slim core but limitless extensibility"} type bulletin struct { Data string PublishedAt time.Time } func main() { f := flamego.Classic() f.Use(template.Templater(), flamego.Renderer()) f.Get("/", func(ctx flamego.Context, t template.Template) { t.HTML(http.StatusOK, "index") }) f.Get("/bulletin", sse.Bind(bulletin{}), func(msg chan<- *bulletin) { for { select { case <-time.Tick(1 * time.Second): msg <- &bulletin{ Data: bulletins[rand.Intn(len(bulletins))], PublishedAt: time.Now(), } } } }) f.Run() }
- Read documentation and examples.
- Please file an issue or start a discussion on the flamego/flamego repository.
This project is under the MIT License. See the LICENSE file for the full license text.