net

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2021 License: MIT Imports: 12 Imported by: 4

README

Go

go-sse

Basic implementation of SSE in golang. This repository includes a plug and play server-side imlementation and a client-side implementation. The server-side implementation has been battle-tested while the client-side is usable but in ongoing development.

Code examples can be found in the example folder.

Install

go get github.com/subchord/go-sse@master

Server side SSE

  1. Create a new broker and pass optional headers that should be sent to the client.
sseClientBroker := net.NewBroker(map[string]string{
	"Access-Control-Allow-Origin": "*",
})
  1. Set the disconnect callback function if you want to be updated when a client disconnects.
sseClientBroker.SetDisconnectCallback(func(clientId string, sessionId string) {
	log.Printf("session %v of client %v was disconnected.", sessionId, clientId)
})
  1. Return an http event stream in an http.Handler. And keep the request open
func (api *API) sseHandler(writer http.ResponseWriter, request *http.Request) {
	clientConn, err := api.broker.Connect("unique_client_reference", writer, request)
	if err != nil {
		log.Println(err)
		return
	}
	<- clientConn.Done()
}
  1. After a connection is established you can broadcast events or send client specific events either through the clientConnection instance or through the broker.
evt := net.StringEvent{
	Id: "self-defined-event-id",
	Event: "type of the event eg. foo_update, bar_delete, ..."
	Data: "data of the event in string format. eg. plain text, json string, ..."
}
api.broker.Broadcast(evt) // all active clients receive this event
api.broker.Send("unique_client_reference", evt) // only the specified client receives this event
&ClientConnection{}.Send(evt) // Send evt through ClientConnection instance. This instance should always be received by the broker.Connect(...) call.

Client side SSE

The SSE client makes extensive use of go channels. Once a connection with an SSE feed is established you can subscribe to multiple types of events and process them by looping over the subscription's feed (channel).

  1. Connect with SSE feed. And pass optional headers.
headers := make(map[string][]string)
feed, err := net.ConnectWithSSEFeed("http://localhost:8080/sse", headers)
if err != nil {
	log.Fatal(err)
	return
}
  1. Subscribe to a specific type of event.
sub, err := feed.Subscribe("message") // or leave empty to receive all event types
if err != nil {
	return
}
  1. Process the events
for {
	select {
	case evt := <-sub.Feed():
		log.Print(evt)
	case err := <-sub.ErrFeed():
		log.Fatal(err)
		return
	}
}
  1. When you are done with all subscriptions and the SSE feed. Don't forget to close the subscriptions and the feed in order to prevent unnecessary network traffic and memory leaks.
sub.Close()
feed.Close()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Broker

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

func NewBroker

func NewBroker(customHeaders map[string]string) *Broker

func (*Broker) Broadcast

func (b *Broker) Broadcast(event Event)

func (*Broker) Close added in v1.0.2

func (b *Broker) Close() error

func (*Broker) Connect

func (b *Broker) Connect(clientId string, w http.ResponseWriter, r *http.Request) (*ClientConnection, error)

func (*Broker) ConnectWithHeartBeatInterval added in v1.0.3

func (b *Broker) ConnectWithHeartBeatInterval(clientId string, w http.ResponseWriter, r *http.Request, interval time.Duration) (*ClientConnection, error)

func (*Broker) GetClientMetadata added in v1.0.4

func (b *Broker) GetClientMetadata(clientId string) (map[string]interface{}, error)

func (*Broker) IsClientPresent

func (b *Broker) IsClientPresent(clientId string) bool

func (*Broker) Send

func (b *Broker) Send(clientId string, event Event) error

func (*Broker) SetClientMetadata added in v1.0.4

func (b *Broker) SetClientMetadata(clientId string, metadata map[string]interface{}) error

func (*Broker) SetDisconnectCallback

func (b *Broker) SetDisconnectCallback(cb func(clientId string, sessionId string))

type ClientConnection

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

func (*ClientConnection) Done

func (c *ClientConnection) Done() <-chan interface{}

func (*ClientConnection) Id

func (c *ClientConnection) Id() string

func (*ClientConnection) Send

func (c *ClientConnection) Send(event Event)

func (*ClientConnection) SessionId

func (c *ClientConnection) SessionId() string

type ClientMetadata added in v1.0.4

type ClientMetadata map[string]interface{}

type Event

type Event interface {
	Prepare() []byte
	GetId() string
	GetEvent() string
	GetData() string
}

type HeartbeatEvent

type HeartbeatEvent struct{}

func (HeartbeatEvent) GetData

func (h HeartbeatEvent) GetData() string

func (HeartbeatEvent) GetEvent

func (h HeartbeatEvent) GetEvent() string

func (HeartbeatEvent) GetId

func (h HeartbeatEvent) GetId() string

func (HeartbeatEvent) Prepare

func (h HeartbeatEvent) Prepare() []byte

type JsonEvent added in v1.0.7

type JsonEvent struct {
	Id    string
	Event string
	Data  interface{}
}

func (*JsonEvent) GetData added in v1.0.7

func (j *JsonEvent) GetData() string

func (*JsonEvent) GetEvent added in v1.0.7

func (j *JsonEvent) GetEvent() string

func (*JsonEvent) GetId added in v1.0.7

func (j *JsonEvent) GetId() string

func (*JsonEvent) Prepare added in v1.0.7

func (j *JsonEvent) Prepare() []byte

type SSEError added in v1.0.3

type SSEError struct {
	Message string
}

type SSEFeed

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

func ConnectWithSSEFeed

func ConnectWithSSEFeed(url string, headers map[string][]string) (*SSEFeed, error)

func (*SSEFeed) Close

func (s *SSEFeed) Close()

func (*SSEFeed) Subscribe

func (s *SSEFeed) Subscribe(eventType string) (*Subscription, error)

type StreamingUnsupportedError added in v1.0.3

type StreamingUnsupportedError struct {
	SSEError
}

func NewStreamingUnsupportedError added in v1.0.3

func NewStreamingUnsupportedError(msg string) *StreamingUnsupportedError

func (StreamingUnsupportedError) Error added in v1.0.3

type StringEvent

type StringEvent struct {
	Id    string
	Event string
	Data  string
}

func (StringEvent) GetData

func (e StringEvent) GetData() string

func (StringEvent) GetEvent

func (e StringEvent) GetEvent() string

func (StringEvent) GetId

func (e StringEvent) GetId() string

func (StringEvent) Prepare

func (e StringEvent) Prepare() []byte

type Subscription

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

func (*Subscription) Close

func (s *Subscription) Close()

func (*Subscription) ErrFeed

func (s *Subscription) ErrFeed() <-chan error

func (*Subscription) EventType

func (s *Subscription) EventType() string

func (*Subscription) Feed

func (s *Subscription) Feed() <-chan Event

type UnknownClientError added in v1.0.3

type UnknownClientError struct {
	SSEError
}

func NewUnknownClientError added in v1.0.3

func NewUnknownClientError(clientId string) *UnknownClientError

func (UnknownClientError) Error added in v1.0.3

func (u UnknownClientError) Error() string

Jump to

Keyboard shortcuts

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