sse

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2020 License: MIT Imports: 8 Imported by: 49

README

go-sse

Go Report Card Build Status GoDoc

Server-Sent Events for Go

About

Server-sent events is a method of continuously sending data from a server to the browser, rather than repeatedly requesting it, replacing the "long polling way".

It's supported by all major browsers and for IE/Edge you can use a polyfill.

go-sse is a small library to create a Server-Sent Events server in Go and works with Go 1.9+.

Features

  • Multiple channels (isolated)
  • Broadcast message to all channels
  • Custom headers (useful for CORS)
  • Last-Event-ID support (resend lost messages)
  • Follow SSE specification
  • Compatible with multiple Go frameworks

Instalation

go get github.com/alexandrevicenzi/go-sse

Example

Server side:

package main

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

    "github.com/alexandrevicenzi/go-sse"
)

func main() {
    // Create SSE server
    s := sse.NewServer(nil)
    defer s.Shutdown()

    // Configure the route
    http.Handle("/events/", s)

    // Send messages every 5 seconds
    go func() {
        for {
            s.SendMessage("/events/my-channel", sse.SimpleMessage(time.Now().Format("2006/02/01/ 15:04:05")))
            time.Sleep(5 * time.Second)
        }
    }()

    log.Println("Listening at :3000")
    http.ListenAndServe(":3000", nil)
}

Client side (JavaScript):

e = new EventSource('/events/my-channel');
e.onmessage = function(event) {
    console.log(event.data);
};

More examples available here.

License

MIT

Documentation

Overview

Package sse implements Server-Sent Events that supports multiple channels.

Server-sent events is a method of continuously sending data from a server to the browser, rather than repeatedly requesting it.

Examples

Basic usage of sse package.

s := sse.NewServer(nil)
defer s.Shutdown()

http.Handle("/events/", s)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Channel

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

Channel represents a server sent events channel.

func (*Channel) ClientCount

func (c *Channel) ClientCount() int

ClientCount returns the number of clients connected to this channel.

func (*Channel) Close

func (c *Channel) Close()

Close closes the channel and disconnect all clients.

func (*Channel) LastEventID added in v1.1.0

func (c *Channel) LastEventID() string

LastEventID returns the ID of the last message sent.

func (*Channel) SendMessage

func (c *Channel) SendMessage(message *Message)

SendMessage broadcast a message to all clients in a channel.

type Client

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

Client represents a web browser connection.

func (*Client) Channel

func (c *Client) Channel() string

Channel returns the channel where this client is subscribe to.

func (*Client) LastEventID added in v1.1.0

func (c *Client) LastEventID() string

LastEventID returns the ID of the last message sent.

func (*Client) SendMessage

func (c *Client) SendMessage(message *Message)

SendMessage sends a message to client.

type Message

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

Message represents a event source message.

func NewMessage

func NewMessage(id, data, event string) *Message

NewMessage creates an event source message.

func SimpleMessage

func SimpleMessage(data string) *Message

SimpleMessage creates a simple event source message.

func (*Message) Buffer added in v1.6.0

func (m *Message) Buffer() *bytes.Buffer

Buffer formats the message.

func (*Message) Bytes added in v1.6.0

func (m *Message) Bytes() []byte

Bytes returns the formated message as a byte array.

func (*Message) String

func (m *Message) String() string

String returns the formated message as a string.

type Options

type Options struct {
	// RetryInterval change EventSource default retry interval (milliseconds).
	RetryInterval int
	// Headers allow to set custom headers (useful for CORS support).
	Headers map[string]string
	// ChannelNameFunc allow to create custom channel names.
	// Default channel name is the request path.
	ChannelNameFunc func(*http.Request) string
	// All usage logs end up in Logger
	Logger *log.Logger
}

Options holds server configurations.

type Server

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

Server represents a server sent events server.

func NewServer

func NewServer(options *Options) *Server

NewServer creates a new SSE server.

func (*Server) Channels

func (s *Server) Channels() []string

Channels returns a list of all channels to the server.

func (*Server) ClientCount

func (s *Server) ClientCount() int

ClientCount returns the number of clients connected to this server.

func (*Server) CloseChannel

func (s *Server) CloseChannel(name string)

CloseChannel closes a channel.

func (*Server) GetChannel

func (s *Server) GetChannel(name string) (*Channel, bool)

GetChannel returns the channel associated with name or nil if not found.

func (*Server) HasChannel

func (s *Server) HasChannel(name string) bool

HasChannel returns true if the channel associated with name exists.

func (*Server) Restart

func (s *Server) Restart()

Restart closes all channels and clients and allow new connections.

func (*Server) SendMessage

func (s *Server) SendMessage(channelName string, message *Message)

SendMessage broadcast a message to all clients in a channel. If channelName is an empty string, it will broadcast the message to all channels.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(response http.ResponseWriter, request *http.Request)

func (*Server) Shutdown

func (s *Server) Shutdown()

Shutdown performs a graceful server shutdown.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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