sse

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2023 License: MIT Imports: 5 Imported by: 0

README

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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind

func Bind(obj interface{}, opts ...Options) flamego.Handler

Bind returns a middleware handler that uses the given bound object as the date type for sending events.

Types

type Options

type Options struct {
	// PingInterval is the time internal to wait between sending pings to the
	// client. Default is 10 seconds.
	PingInterval time.Duration
}

Options contains options for the sse.Bind middleware.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL