sse

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2021 License: MIT Imports: 7 Imported by: 2

README

HTML5 Server-Sent Events for Go

See http://www.w3.org/TR/eventsource/ for the technical specification.

import "github.com/mdigger/sse"


var sse = new(sse.Server)

type Event struct {
    ID   int       `json:"id"`
    Time time.Time `json:"time"`
}

go func() {
    var id int
    for range time.Tick(5 * time.Second) {
        id++
        sse.Event(fmt.Sprintf("%04d", id), "event", 
        &Event{
            ID:   id,
            Time: time.Now().Truncate(time.Second),
        })
    }
}()

http.Handle("/events", sse)
log.Fatal(http.ListenAndServe(":8000", nil))

Documentation

Overview

Package sse provides HTML5 Server-Sent Events for Go.

See http://www.w3.org/TR/eventsource/ for the technical specification.

Example
package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/mdigger/sse"
)

func main() {
	type Event struct {
		ID   int       `json:"id"`
		Time time.Time `json:"time"`
	}

	var sse = new(sse.Server)
	go func() {
		var id int
		for range time.Tick(5 * time.Second) {
			id++
			_ = sse.Event(fmt.Sprintf("%04d", id), "event", &Event{
				ID:   id,
				Time: time.Now().Truncate(time.Second),
			})
		}
	}()
	http.Handle("/events", sse)
	log.Fatal(http.ListenAndServe(":8000", nil))
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server provides HTML5 Server-Sent Events

func (*Server) Close

func (s *Server) Close()

Close closes the server and disconnect all clients.

func (*Server) Comment

func (s *Server) Comment(text string)

Comment sends an comment with the given text to all connected clients.

func (*Server) Connected

func (s *Server) Connected() int

Connected return number of connected clients.

func (*Server) Event

func (s *Server) Event(id, name string, v interface{}) error

Event sends an event with the given data encoded as JSON to all connected clients.

func (*Server) Retry

func (s *Server) Retry(d time.Duration)

Retry sends all clients an indication of the delay in restoring the connection.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface.

Jump to

Keyboard shortcuts

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