Skip to content
/ sse Public

Package sse is a middleware that provides Server-Sent Events for Flamego

License

Notifications You must be signed in to change notification settings

flamego/sse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sse

GitHub Workflow Status Codecov GoDoc Sourcegraph

Package sse is a middleware that provides Server-Sent Events for Flamego.

Installation

The minimum requirement of Go is 1.18.

go get github.com/flamego/sse

Getting started

<!-- 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()
}

Getting help

License

This project is under the MIT License. See the LICENSE file for the full license text.