sse

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2024 License: MIT Imports: 7 Imported by: 0

README

Server-Sent Events (SSE) handler

Go Reference Go Tests

Server-Sent Events (SSE) handler is a generic and http.Handler compliant module, that implements real-time event streaming from a server to web clients using the Server-Sent Events protocol. It's a robust module for managing multiple client connections, broadcasting events, and handling client registrations and unregistrations efficiently.

Examples of using this module can be found from the ./examples directory.

Prerequisites

  • Go 1.23.0 or above

Installation

go get -u github.com/softwarespot/sse

Usage

A basic example of using SSE.

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/softwarespot/sse"
)

func main() {
    // Use the default configuration
    h := sse.New[int](nil)
    defer h.Close()

    go func() {
        var evt int
        for {
            fmt.Println("sse handler: broadcast event", h.Broadcast(evt))
            evt++
            time.Sleep(64 * time.Millisecond)
        }
    }()

    http.Handle("/events", h)
    http.ListenAndServe(":3000", nil)
}

License

The code has been licensed under the MIT license.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config[T any] struct {
	// How often to flush the events to the connected clients. Default is 256ms
	FlushFrequency time.Duration

	// How long to wait for all connected client to gracefully close. Default is 30s
	CloseTimeout time.Duration

	// Replay events when a client connects
	Replay struct {
		// How many events to send in chunks, when a client connects. Default is 256 events
		Initial int

		// How many events to keep in memory. Default is 2048 events
		Maximum int

		// How long an event should be kept in memory for. Default is 30s
		Expiry time.Duration
	}

	// Events encoder function, which returns a slice of bytes that will then be converted to a string. Default is json.Marshal()
	Encoder func([]T) ([]byte, error)
}

Config defines the configuration settings for the Server-Sent Events (SSE) handler.

func NewConfig

func NewConfig[T any]() *Config[T]

NewConfig initializes a configuration instance with reasonable defaults.

type Handler

type Handler[T any] struct {
	// contains filtered or unexported fields
}

Handler is a generic Server-Sent Events (SSE) handler.

func New

func New[T any](cfg *Config[T]) *Handler[T]

New initializes a Server-Sent Events (SSE) handler, with an optional configuration. If the provided configuration is nil, then it uses the default configuration.

Example
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/softwarespot/sse"
)

func main() {
	// Use the default configuration
	h := sse.New[int](nil)
	defer h.Close()

	go func() {
		var evt int
		for {
			fmt.Println("sse handler: broadcast event", h.Broadcast(evt))
			evt++
			time.Sleep(64 * time.Millisecond)
		}
	}()

	http.Handle("/events", h)
	http.ListenAndServe(":3000", nil)
}
Output:

func (*Handler[T]) Broadcast

func (h *Handler[T]) Broadcast(evts ...T) error

Broadcast broadcasts one or more events to all the connected clients. It returns an error if the handler is closed.

func (*Handler[T]) Close

func (h *Handler[T]) Close() error

Close closes the Server-Sent Events (SSE) handler. It waits for all clients to complete/close, with a timeout defined in the configuration.

func (*Handler[T]) ServeHTTP

func (h *Handler[T]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for the Server-Sent Events (SSE) handler. It calls ServeSSE and handles any errors by writing an HTTP error response with status code 500.

func (*Handler[T]) ServeSSE

func (h *Handler[T]) ServeSSE(w http.ResponseWriter, r *http.Request) error

ServeSSE serves the Server-Sent Events (SSE) to the HTTP response writer. It sets the appropriate headers and streams events to the client until the connection is closed.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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