agentleFS
jkanindajkaninda/okapi-skills/sse_stream/SKILL.md

sse_stream

Skill3 starsChanged 3 months agoMITView on GitHub

Okapi provides built-in SSE support for real-time server-to-client streaming over HTTP. SSE connections are long-lived GET requests where the server pushes events using the text/event-stream content type. The framework handles headers, flushing, keep-alive pings, and serialization automatically. c.SendSSEvent(id, eventType, data) is deprecated — use c.SSESendEvent(...). Each helper writes the frame and flushes it, so events reach the client immediately. okapi.LoggerMiddleware skips SSE requests, keeping long-lived streams out of the access log. A Message can also be written directly to any…

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use SSEStreamWithOptions for keep-alive pings, custom serializers, and error handling:

    line 116

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Okapi SSE (Server-Sent Events) Skills

Okapi provides built-in SSE support for real-time server-to-client streaming over HTTP. SSE connections are long-lived GET requests where the server pushes events using the text/event-stream content type. The framework handles headers, flushing, keep-alive pings, and serialization automatically.

Core Types

TypeDescription
MessageSingle SSE message with ID, Event, Data, Retry, Serializer fields
StreamOptionsAdvanced stream config: Serializer, PingInterval, OnError callback
SerializerInterface: Serialize(data any) (string, error) — custom data encoding
SendFuncfunc(data any, eventType string) (string, error)

Built-in Serializers

SerializerDescription
okapi.JSONSerializerDefault — marshals data as JSON
okapi.TextSerializerPlain text via fmt.Sprintf("%v", data)
okapi.Base64SerializerBase64-encodes []byte data

Sending Single Events

// Fire-and-forget event (no ID, auto-generated internally)
c.SSEvent("message", data)

// Event with explicit ID
c.SSESendEvent("event-1", "message", data)

// Data-only (no event type)
c.SSESendData(data)

// Explicit serializer variants
c.SSESendJSON(data)            // JSON serializer
c.SSESendText("hello")         // Text serializer
c.SSESendBinary([]byte{...})   // Base64 serializer
c.SendSSECustom(data, mySerializer)  // Custom serializer

c.SendSSEvent(id, eventType, data) is deprecated — use c.SSESendEvent(...).

Each helper writes the frame and flushes it, so events reach the client immediately. okapi.LoggerMiddleware skips SSE requests, keeping long-lived streams out of the access log.

A Message can also be written directly to any http.ResponseWriter:

msg := okapi.Message{Event: "update", Data: payload}
id, err := msg.Send(c.Response())   // writes the frame, returns the message ID
err = msg.Close(c.Response())       // flush

Simple Event Loop (Recommended for Most Cases)

The simplest pattern — use a ticker and send events directly in a loop:

app.Get("/events", func(c *okapi.Context) error {
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()

    ctx := c.Request().Context()
    for {
        select {
        case <-ctx.Done():
            return nil
        case t := <-ticker.C:
            data := okapi.M{
                "time":      t.Format("15:04:05"),
                "timestamp": t.Unix(),
            }
            if err := c.SSEvent("message", data); err != nil {
                return err
            }
        }
    }
})

Channel-Based Streaming

For producer/consumer patterns, use SSEStream with a message channel:

app.Get("/events", func(c *okapi.Context) error {
    ctx, cancel := context.WithCancel(c.Request().Context())
    defer cancel()

    messageChan := make(chan okapi.Message, 10)

    // Producer goroutine
    go func() {
        defer close(messageChan)
        ticker := time.NewTicker(1 * time.Second)
        defer ticker.Stop()

        for i := 0; ; i++ {
            select {
            case <-ctx.Done():
                return
            case t := <-ticker.C:
                messageChan <- okapi.Message{
                    Event: "update",
                    Data:  okapi.M{"time": t.Format("15:04:05"), "count": i},
                }
            }
        }
    }()

    return c.SSEStream(ctx, messageChan)
})

Advanced Streaming with Options

Use SSEStreamWithOptions for keep-alive pings, custom serializers, and error handling:

app.Get("/events", func(c *okapi.Context) error {
    ctx, cancel := context.WithCancel(c.Request().Context())
    defer cancel()

    messageChan := make(chan okapi.Message, 10)

    go func() {
        defer close(messageChan)
        // ... produce messages ...
    }()

    return c.SSEStreamWithOptions(ctx, messageChan, &okapi.StreamOptions{
        Serializer:   &okapi.JSONSerializer{},
        PingInterval: 30 * time.Second,
        OnError: func(err error) {
            slog.Error("SSE stream error", "error", err)
        },
    })
})

Detecting SSE Requests

if c.IsSSE() {
    // Request has Accept: text/event-stream and method is GET
}

SSE Message Fields

FieldTypeDescription
IDstringMessage identifier (auto-generated UUID if empty)
EventstringEvent type (client listens via addEventListener)
DataanyPayload — auto-serialized based on type or Serializer
RetryuintClient reconnection interval in milliseconds
SerializerSerializerPer-message serializer (overrides stream-level)

StreamOptions Fields

FieldTypeDescription
SerializerSerializerDefault serializer for all messages in stream
PingIntervaltime.DurationKeep-alive ping interval (sends : ping comments)
OnErrorfunc(error)Error callback for send/ping failures

Custom Serializer

Implement the Serializer interface for custom data formats:

type XMLSerializer struct{}

func (x XMLSerializer) Serialize(data any) (string, error) {
    b, err := xml.Marshal(data)
    if err != nil {
        return "", err
    }
    return string(b), nil
}

// Use per-message
c.SendSSECustom(data, XMLSerializer{})

// Or stream-level
c.SSEStreamWithOptions(ctx, ch, &okapi.StreamOptions{
    Serializer: XMLSerializer{},
})

Client-Side (JavaScript)

const eventSource = new EventSource('/events');

// Listen for named events
eventSource.addEventListener('message', (event) => {
    const data = JSON.parse(event.data);
    console.log(data);
});

// Handle errors and reconnect
eventSource.onerror = () => {
    eventSource.close();
    setTimeout(() => { /* reconnect */ }, 3000);
};

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.