sse

package
v7.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2024 License: MIT Imports: 6 Imported by: 1

README

Server-Sent Events

This extension provides support for Server-Sent Events for any net/http compliant http server. It provides the following hooks for customizing the workflows:

  1. OnCreateClient func(ctx context.Context, client *Client, count int)
  2. OnRemoveClient func(ctx context.Context, clientID string, count int)
  3. OnSend func(ctx context.Context, client *Client, err error)
  4. BeforeSend func(ctx context.Context, client *Client)
import (
    "github.com/bnkamalesh/webgo/extensions/sse"
)
func main() {
    sseService := sse.New()
    // broadcast to all active clients
    sseService.Broadcast(Message{
        Data:  "Hello world",
        Retry: time.MilliSecond,
	})

	// You can replace the ClientManager with your custom implementation, and override the default one
	// sseService.Clients = <your custom client manager>

    // send message to an individual client
    clientID := "cli123"
    cli := sseService.Client(clientID)
    if cli != nil {
        cli.Message <- &Message{Data: fmt.Sprintf("Hello %s",clientID), Retry: time.MilliSecond }
    }
}

Client Manager

Client manager is an interface which is required for SSE to function, since this is an interface it's easier for you to replace if required. The default implementation is a simple one using mutex. If you have a custom implementation which is faster/better, you can easily swap out the default one.

type ClientManager interface {
	// New should return a new client, and the total number of active clients after adding this new one
	New(ctx context.Context, w http.ResponseWriter, clientID string) (*Client, int)
	// Range should iterate through all the active clients
	Range(func(*Client))
	// Remove should remove the active client given a clientID, and close the connection
	Remove(clientID string) int
	// Active returns the number of active clients
	Active() int
	// Clients returns a list of all active clients
	Clients() []*Client
	// Client returns *Client if clientID is active
	Client(clientID string) *Client
}

Documentation

Overview

Package sse implements Server-Sent Events(SSE) This extension is compliant with any net/http implementation, and is not limited to WebGo.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultBeforeSend

func DefaultBeforeSend(ctx context.Context, client *Client)

func DefaultCreateHook

func DefaultCreateHook(ctx context.Context, client *Client, count int)

func DefaultOnSend

func DefaultOnSend(ctx context.Context, client *Client, err error)

func DefaultRemoveHook

func DefaultRemoveHook(ctx context.Context, clientID string, count int)

func DefaultUnsupportedMessageHandler

func DefaultUnsupportedMessageHandler(w http.ResponseWriter, r *http.Request) error

Types

type Client

type Client struct {
	ID             string
	Msg            chan *Message
	ResponseWriter http.ResponseWriter
	Ctx            context.Context
}

type ClientManager

type ClientManager interface {
	// New should return a new client, and the total number of active clients after adding this new one
	New(ctx context.Context, w http.ResponseWriter, clientID string) (*Client, int)
	// Range should iterate through all the active clients
	Range(func(*Client))
	// Remove should remove the active client given a clientID, and close the connection
	Remove(clientID string) int
	// Active returns the number of active clients
	Active() int
	// Clients returns a list of all active clients
	Clients() []*Client
	// Client returns *Client if clientID is active
	Client(clientID string) *Client
}

func NewClientManager

func NewClientManager() ClientManager

type Clients

type Clients struct {
	MsgBuffer int
	// contains filtered or unexported fields
}

func (*Clients) Active

func (cs *Clients) Active() int

func (*Clients) Client

func (cs *Clients) Client(clientID string) *Client

func (*Clients) Clients

func (cs *Clients) Clients() []*Client

MessageChannels returns a slice of message channels of all clients which you can then use to send message concurrently

func (*Clients) New

func (cs *Clients) New(ctx context.Context, w http.ResponseWriter, clientID string) (*Client, int)

func (*Clients) Range

func (cs *Clients) Range(f func(cli *Client))

func (*Clients) Remove

func (cs *Clients) Remove(clientID string) int

type Message

type Message struct {
	// Event is a string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message.
	Event string

	// Data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it concatenates them, inserting a newline character between each one. Trailing newlines are removed.
	Data string

	// ID to set the EventSource object's last event ID value.
	ID string

	// Retry is the reconnection time. If the connection to the server is lost, the browser will wait for the specified time before attempting to reconnect. This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
	Retry time.Duration
}

Message represents a valid SSE message ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

func (*Message) Bytes

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

type SSE

type SSE struct {
	// ClientIDHeader is the HTTP request header in which the client ID is set. Default is `sse-clientid`
	ClientIDHeader string
	// UnsupportedMessage is used to send the error response to client if the
	// server doesn't support SSE
	UnsupportedMessage func(http.ResponseWriter, *http.Request) error

	// OnCreateClient is a hook, for when a client is added to the active clients. count is the number
	// of active clients after adding the latest client
	OnCreateClient func(ctx context.Context, client *Client, count int)

	// OnRemoveClient is a hook, for when a client is removed from the active clients. count is the number
	// of active clients after removing a client
	OnRemoveClient func(ctx context.Context, clientID string, count int)

	// OnSend is a hook, which is called *after* a message is sent to a client
	OnSend func(ctx context.Context, client *Client, err error)
	// BeforeSend is a hook, which is called right before a message is sent to a client
	BeforeSend func(ctx context.Context, client *Client)

	Clients ClientManager
}

func New

func New() *SSE

func (*SSE) ActiveClients

func (sse *SSE) ActiveClients() int

func (*SSE) Broadcast

func (sse *SSE) Broadcast(msg Message)

Broadcast sends the message to all active clients

func (*SSE) Client

func (sse *SSE) Client(id string) *Client

func (*SSE) Handler

func (sse *SSE) Handler(w http.ResponseWriter, r *http.Request) error

Handler returns an error rather than being directly used as an http.HandlerFunc, to let the user handle error. e.g. if the error has to be logged

func (*SSE) HandlerFunc

func (sse *SSE) HandlerFunc(w http.ResponseWriter, r *http.Request)

HandlerFunc is a convenience function which can be directly used with net/http implementations. Important: You cannot handle any error returned by the Handler

func (*SSE) NewClient

func (sse *SSE) NewClient(ctx context.Context, w http.ResponseWriter, clientID string) *Client

func (*SSE) RemoveClient

func (sse *SSE) RemoveClient(ctx context.Context, clientID string)

Jump to

Keyboard shortcuts

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