sse

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package sse serves Server-Sent Events: a one-way text/event-stream from server to client. Handler wraps a streaming writer; the supplied function owns the send loop and returns to end the stream.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handler

func Handler(fn func(c *fiber.Ctx, s *Stream)) fiber.Handler

Handler returns a Fiber handler that streams events. fn is called with a Stream; when fn returns, the stream closes. fn owns its own loop and should stop when a Send returns an error (client gone) or the request context is done.

Example
package main

import (
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/rahmadafandi/fibr/sse"
)

func main() {
	app := fiber.New()
	app.Get("/events", sse.Handler(func(c *fiber.Ctx, s *sse.Stream) {
		ticker := time.NewTicker(time.Second)
		defer ticker.Stop()
		for n := 0; ; n++ {
			if err := s.Send("tick", map[string]int{"n": n}); err != nil {
				return // client disconnected
			}
			select {
			case <-c.Context().Done():
				return
			case <-ticker.C:
			}
		}
	}))
	_ = app
}

Types

type Event

type Event struct {
	ID    string
	Name  string
	Data  any
	Retry int // reconnection hint, milliseconds
}

Event is a fully specified SSE event. Data is JSON-encoded unless it is a string or []byte, which are written verbatim.

type Stream

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

Stream writes SSE frames to a single client connection.

func (*Stream) Comment

func (s *Stream) Comment(text string) error

Comment writes an SSE comment line (": text"), commonly used as a keepalive.

func (*Stream) Event

func (s *Stream) Event(e Event) error

Event writes a fully specified event and flushes. A flush error indicates the client disconnected.

func (*Stream) Send

func (s *Stream) Send(event string, data any) error

Send writes a named event with JSON-encoded data and flushes.

func (*Stream) SendRaw

func (s *Stream) SendRaw(event, data string) error

SendRaw writes a named event with a pre-formatted string payload.

Jump to

Keyboard shortcuts

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