Code Monkey home page Code Monkey logo

go-sse's Introduction

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()

go-sse's People

Contributors

subchord avatar kaatinga avatar pveeckhout avatar rajatjindal avatar shairozan avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.