https://github.com/bmhatfield/sse
Server sent events publisher in Go
https://github.com/bmhatfield/sse
go golang http push server-sent-events sse
Last synced: 3 months ago
JSON representation
Server sent events publisher in Go
- Host: GitHub
- URL: https://github.com/bmhatfield/sse
- Owner: bmhatfield
- License: apache-2.0
- Created: 2023-08-03T23:46:19.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-01-13T15:41:48.000Z (over 1 year ago)
- Last Synced: 2025-01-23T21:29:20.396Z (4 months ago)
- Topics: go, golang, http, push, server-sent-events, sse
- Language: Go
- Homepage:
- Size: 16.6 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://pkg.go.dev/github.com/bmhatfield/sse)
# github.com/bmhatfield/sse
[Server sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) publisher in Go## Install
`go get github.com/bmhatfield/sse`
## Usage
Import sse
```go
import "github.com/bmhatfield/sse"
```Create the event server. The event server is an async topic publisher, with events pushed to active subscribers.
```go
// Create event server.
events := sse.NewEventServer()// Create initial topic
events.Create("topic-name")
```Create an event, and then broadcast it to subscribers. Messages will be sent to active subscribers. Broadcasts to non-existent topics will fail. Broadcasts to topics without subscribers will be dropped.
```go
// Create an event
// See also: JSONEvent, or implement your own Event!
event := sse.NewEvent("optional-kind", []byte("hi!"))// Broadcast!
if err := events.Broadcast("topic-name", event); err != nil {
log.Printf("failed to broadcast: %s", err)
}
```The event server is a simple HTTP handler. Use with your favorite router, or serve with the standard library.
```go
// Serve event stream
http.Handle("/events", events)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
```Use EventSource in `js` to listen for events. Clients can select their stream with the `stream` query param.
```js
const stream = new EventSource("/events?stream=points");
```