sse

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 9 Imported by: 0

README

sse

Server-Sent Events hub for real-time client communication with pattern-based broadcasting.

Install

go get github.com/kbukum/gokit

Quick Start

package main

import (
    "net/http"
    "github.com/kbukum/gokit/sse"
)

func main() {
    hub := sse.NewHub()
    go hub.Run()

    // SSE endpoint
    http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
        clientID := r.URL.Query().Get("id")
        sse.ServeSSE(hub, w, r, clientID,
            sse.WithUserID("user-123"),
            sse.WithMetadata("role", "admin"),
        )
    })

    // Broadcast to clients matching a pattern
    hub.BroadcastToPattern("user-*", []byte(`{"type":"update","data":"hello"}`))

    http.ListenAndServe(":8080", nil)
}

Key Types & Functions

Name Description
Hub Manages SSE client connections and broadcasting
Client Connected SSE client with metadata
NewHub() / Run() Create and start the hub
ServeSSE() HTTP handler for SSE connections
BroadcastToPattern() Send data to clients matching a pattern
Broadcaster Interface for broadcasting events
WithUserID() / WithSessionID() / WithMetadata() Client options
EventType* Constants: connected, keepalive, message, error, metric

⬅ Back to main README

Documentation

Overview

Package sse provides Server-Sent Events (SSE) support for real-time streaming.

Package sse provides Server-Sent Events (SSE) infrastructure for real-time event delivery in gokit applications.

It includes client connection management, event broadcasting to multiple subscribers, and a hub for managing event channels.

Architecture

  • Hub: Central event router managing client subscriptions
  • Broadcaster: Sends events to all connected clients
  • Handler: HTTP handler for SSE endpoint

Usage

hub := sse.NewHub()
go hub.Run()
handler := sse.NewHandler(hub)
router.GET("/events", handler.ServeHTTP)

Package sse provides Server-Sent Events (SSE) support for real-time streaming.

Index

Constants

View Source
const (
	// EventTypeConnected is sent when a client successfully connects.
	EventTypeConnected = "connected"

	// EventTypeKeepAlive is used for keep-alive comments.
	EventTypeKeepAlive = "keepalive"

	// EventTypeMessage is a generic message event.
	EventTypeMessage = "message"

	// EventTypeError is sent when an error occurs.
	EventTypeError = "error"

	// EventTypeMetric is sent for metric/telemetry events.
	EventTypeMetric = "metric"
)

Generic SSE event type constants (infrastructure only). Domain-specific event types should be defined in your application.

Variables

This section is empty.

Functions

func ServeSSE

func ServeSSE(hub *Hub, w http.ResponseWriter, r *http.Request, clientID string, opts ...ClientOption)

ServeSSE handles an SSE connection for a specific client. This is the main entry point called from HTTP handlers.

Types

type Broadcaster

type Broadcaster interface {
	// BroadcastToPattern sends data to all clients matching the given pattern.
	// Pattern uses glob-style matching (e.g., "resource:*" or "resource:abc123").
	BroadcastToPattern(pattern string, data []byte)
}

Broadcaster is an interface for broadcasting events to clients. This allows handlers to depend on an abstraction rather than a concrete Hub.

type Client

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

Client represents a connected SSE client.

func NewClient

func NewClient(id string, opts ...ClientOption) *Client

NewClient creates a new SSE client with optional metadata.

func (*Client) Close

func (c *Client) Close()

Close closes the client's event channel.

func (*Client) Events

func (c *Client) Events() <-chan []byte

Events returns the channel for receiving events.

func (*Client) GetMetadata

func (c *Client) GetMetadata(key string) string

GetMetadata returns a specific metadata value.

func (*Client) ID

func (c *Client) ID() string

ID returns the client's unique identifier.

func (*Client) Metadata

func (c *Client) Metadata() map[string]string

Metadata returns all client metadata.

func (*Client) Send

func (c *Client) Send(data []byte) bool

Send sends data to the client's event channel. Returns false if the channel is full (client is slow).

func (*Client) SessionID

func (c *Client) SessionID() string

SessionID returns the client's session ID (convenience method).

func (*Client) UserID

func (c *Client) UserID() string

UserID returns the client's user ID (convenience method).

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithMetadata

func WithMetadata(key, value string) ClientOption

WithMetadata adds a metadata key-value pair to the client.

func WithSessionID

func WithSessionID(sessionID string) ClientOption

WithSessionID sets the session ID metadata.

func WithUserID

func WithUserID(userID string) ClientOption

WithUserID sets the user ID metadata.

type Component

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

Component wraps an SSE Hub as a lifecycle-managed component. Register it with the component registry so Start/Stop are handled automatically.

func NewComponent

func NewComponent(path string) *Component

NewComponent creates a new SSE component with a fresh Hub.

func (*Component) Describe

func (c *Component) Describe() component.Description

Describe returns infrastructure summary info for the bootstrap display.

func (*Component) Health

func (c *Component) Health(_ context.Context) component.Health

Health returns the health status of the SSE hub.

func (*Component) Hub

func (c *Component) Hub() *Hub

Hub returns the underlying Hub for event broadcasting and client management.

func (*Component) Name

func (c *Component) Name() string

Name returns the component name.

func (*Component) Start

func (c *Component) Start(_ context.Context) error

Start launches the Hub's event loop in a background goroutine.

func (*Component) Stop

func (c *Component) Stop(_ context.Context) error

Stop signals the Hub to shut down and waits for Run to return.

type ConnectedEvent

type ConnectedEvent struct {
	ClientID  string            `json:"client_id"`
	UserID    string            `json:"user_id,omitempty"`
	SessionID string            `json:"session_id,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

ConnectedEvent is sent when a client successfully connects.

type Hub

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

Hub manages SSE client connections and message broadcasting.

func NewHub

func NewHub() *Hub

NewHub creates a new SSE hub.

func (*Hub) BroadcastToPattern

func (h *Hub) BroadcastToPattern(pattern string, data []byte)

BroadcastToPattern sends data to all clients matching the pattern. Pattern uses glob-style matching (e.g., "execution:*" or "execution:abc123").

func (*Hub) GetClient

func (h *Hub) GetClient(id string) *Client

GetClient returns a client by ID, or nil if not found.

func (*Hub) GetClientCount

func (h *Hub) GetClientCount() int

GetClientCount returns the number of connected clients.

func (*Hub) GetClientIDs

func (h *Hub) GetClientIDs() []string

GetClientIDs returns a list of all connected client IDs.

func (*Hub) Register

func (h *Hub) Register(client *Client)

Register adds a client to the hub.

func (*Hub) Run

func (h *Hub) Run()

Run starts the hub's main event loop. It blocks until Stop is called or the context is canceled. This should be run in a goroutine.

func (*Hub) Stop

func (h *Hub) Stop()

Stop signals the hub to shut down. It closes all client connections and causes Run to return. Safe to call multiple times.

func (*Hub) Unregister

func (h *Hub) Unregister(client *Client)

Unregister removes a client from the hub.

type Message

type Message struct {
	Pattern string // Glob pattern for matching clients
	Data    []byte // Event data to send
}

Message represents a message to broadcast.

Jump to

Keyboard shortcuts

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