sseutil

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 10 Imported by: 0

README

go-sseutil

CI Go Reference License

Server-Sent Events (SSE) utilities for Go. Server broker and client, zero dependencies

Installation

go get github.com/philiprehberger/go-sseutil

Usage

Server (Broker)
package main

import (
	"net/http"
	"time"

	"github.com/philiprehberger/go-sseutil"
)

func main() {
	broker := sseutil.NewBroker(sseutil.WithKeepAlive(15 * time.Second))

	http.Handle("/events", broker.Handler())

	go func() {
		for {
			broker.Broadcast(sseutil.Event{
				Event: "tick",
				Data:  "hello",
			})
			time.Sleep(1 * time.Second)
		}
	}()

	http.ListenAndServe(":8080", nil)
}
Client
package main

import (
	"context"
	"fmt"

	"github.com/philiprehberger/go-sseutil"
)

func main() {
	ctx := context.Background()
	stream, err := sseutil.Connect(ctx, "http://localhost:8080/events")
	if err != nil {
		panic(err)
	}
	defer stream.Close()

	for event := range stream.Events() {
		fmt.Printf("Event: %s, Data: %s\n", event.Event, event.Data)
	}
}
JSON Events
// Send JSON to a specific client.
type Message struct {
	Text string `json:"text"`
	From string `json:"from"`
}

err := broker.SendJSON("client-1", "chat", Message{Text: "hi", From: "alice"})
// Sends: event: chat\ndata: {"text":"hi","from":"alice"}\n\n

// Broadcast JSON to all clients.
err = broker.BroadcastJSON("update", map[string]any{"status": "ok"})
Topics
// Subscribe a client to topics.
broker.Subscribe("client-1", "sports", "news")

// Publish to a topic — only subscribed clients receive the event.
broker.PublishTopic("sports", sseutil.Event{Event: "score", Data: "3-2"})
Lifecycle Hooks
broker.OnConnect(func(clientID string) {
	log.Printf("client connected: %s", clientID)
})

broker.OnDisconnect(func(clientID string) {
	log.Printf("client disconnected: %s", clientID)
})
Event Builder
event := sseutil.Event{
	ID:    "1",
	Event: "update",
	Data:  "payload data",
	Retry: 5000,
}

fmt.Print(event.String())
// Output:
// id: 1
// event: update
// data: payload data
// retry: 5000

API

Type / Function Description
Event SSE event with ID, Event, Data, and Retry fields
Event.Bytes() Encode event to SSE wire format
Event.String() String representation of SSE event
Broker Manages SSE client connections
NewBroker(opts...) Create a new broker with options
WithKeepAlive(d) Set keep-alive interval (default 30s)
Broker.Handler() HTTP handler for SSE endpoint
Broker.Broadcast(e) Send event to all clients
Broker.Send(id, e) Send event to a specific client
Broker.SendJSON(id, event, data) Marshal data to JSON and send to a client
Broker.BroadcastJSON(event, data) Marshal data to JSON and broadcast to all
Broker.Subscribe(id, topics...) Subscribe a client to named topics
Broker.PublishTopic(topic, e) Send event to all clients subscribed to topic
Broker.OnConnect(fn) Set callback for client connections
Broker.OnDisconnect(fn) Set callback for client disconnections
Broker.ClientCount() Number of connected clients
Connect(ctx, url) Connect to an SSE endpoint
Stream.Events() Channel of received events
Stream.Close() Close the connection
Stream.LastEventID() Last received event ID

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package sseutil provides Server-Sent Events utilities for Go.

It includes a server-side broker for managing SSE client connections and broadcasting events, a client for consuming SSE streams, and an event builder for constructing SSE-formatted messages.

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
}

Broker manages Server-Sent Events client connections. It supports broadcasting events to all connected clients, sending events to specific clients, and automatic keep-alive pings.

func NewBroker

func NewBroker(opts ...BrokerOption) *Broker

NewBroker creates a new SSE broker with the given options.

func (*Broker) Broadcast

func (b *Broker) Broadcast(event Event)

Broadcast sends an event to all connected clients. Events are dropped for clients whose send buffers are full.

func (*Broker) BroadcastJSON added in v0.2.0

func (b *Broker) BroadcastJSON(event string, data any) error

BroadcastJSON marshals data to JSON and broadcasts it as an SSE event to all connected clients. It returns an error if JSON marshaling fails.

func (*Broker) ClientCount

func (b *Broker) ClientCount() int

ClientCount returns the number of currently connected clients.

func (*Broker) Handler

func (b *Broker) Handler() http.Handler

Handler returns an http.Handler that serves as an SSE endpoint.

It sets the appropriate headers (Content-Type, Cache-Control, Connection), registers the client, streams events, and removes the client on disconnect.

func (*Broker) OnConnect added in v0.2.0

func (b *Broker) OnConnect(fn func(clientID string))

OnConnect sets a callback function that is invoked when a new client connects. The callback receives the client ID.

func (*Broker) OnDisconnect added in v0.2.0

func (b *Broker) OnDisconnect(fn func(clientID string))

OnDisconnect sets a callback function that is invoked when a client disconnects. The callback receives the client ID.

func (*Broker) PublishTopic added in v0.2.0

func (b *Broker) PublishTopic(topic string, event Event)

PublishTopic sends an event to all clients subscribed to the given topic. Events are dropped for clients whose send buffers are full.

func (*Broker) Send

func (b *Broker) Send(clientID string, event Event) bool

Send sends an event to a specific client identified by clientID. It returns false if the client was not found.

func (*Broker) SendJSON added in v0.2.0

func (b *Broker) SendJSON(clientID string, event string, data any) error

SendJSON marshals data to JSON and sends it as an SSE event to the specified client. It returns an error if JSON marshaling fails, or if the client was not found.

func (*Broker) Subscribe added in v0.2.0

func (b *Broker) Subscribe(clientID string, topics ...string)

Subscribe adds the given client to the specified topics. If the client is not connected, the subscription is still recorded and will take effect if the client connects with the same ID.

type BrokerOption

type BrokerOption func(*Broker)

BrokerOption configures a Broker.

func WithKeepAlive

func WithKeepAlive(d time.Duration) BrokerOption

WithKeepAlive sets the interval for sending keep-alive comment lines to connected clients. The default is 30 seconds. Set to 0 to disable.

type Event

type Event struct {
	// ID is the event identifier. If non-empty, it is sent as the "id" field.
	ID string

	// Event is the event type. If non-empty, it is sent as the "event" field.
	Event string

	// Data is the event payload. It is always included in the SSE output.
	// Multi-line data is split so each line is prefixed with "data: ".
	Data string

	// Retry is the reconnection interval in milliseconds.
	// If zero, the retry field is omitted from the output.
	Retry int
}

Event represents a Server-Sent Event with standard fields.

func (Event) Bytes

func (e Event) Bytes() []byte

Bytes encodes the event into SSE wire format.

Only non-empty fields are included, except Data which is always present. Multi-line data values are split on newline characters, with each line emitted as a separate "data:" field.

func (Event) String

func (e Event) String() string

String returns the SSE-formatted event as a string.

type Stream

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

Stream is an SSE client that connects to an SSE endpoint and parses incoming events into a channel.

func Connect

func Connect(ctx context.Context, url string) (*Stream, error)

Connect establishes a connection to the given SSE endpoint URL and returns a Stream that emits parsed events. The context controls the lifetime of the connection.

func (*Stream) Close

func (s *Stream) Close() error

Close closes the SSE stream and releases resources.

func (*Stream) Events

func (s *Stream) Events() <-chan Event

Events returns a receive-only channel of parsed SSE events. The channel is closed when the stream ends or Close is called.

func (*Stream) LastEventID

func (s *Stream) LastEventID() string

LastEventID returns the ID of the last received event.

Jump to

Keyboard shortcuts

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