sse

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: MIT Imports: 13 Imported by: 0

README

SSE (Server-Sent Events) for Go

高性能、易集成的 Server-Sent Events 解决方案,支持纯 Go 服务端与客户端闭环。

Go Version License Beta

特性

  • 开箱即用 - 一行代码启动 SSE 服务
  • 纯 Go 闭环 - 服务端和客户端均为 Go 实现,无需 JavaScript
  • 消息历史 - 支持断线重连后自动补发消息
  • 房间隔离 - 支持消息房间分组
  • 可插拔存储 - 内存存储/Redis/自定义 Storage 接口
  • 高性能 - 基于 Channel 的异步消息分发
  • 自动重连 - 客户端自动重连机制
  • 双向心跳保活 - Server→Client 心跳 + Client→Server ack 超时检测
  • 低依赖 - 最小化外部依赖

安装

go get gitee.com/vipkwds/sse

快速开始

Server (服务端)
package main

import (
    "fmt"
    "net/http"

    "gitee.com/vipkwds/sse"
)

func main() {
    // 创建 SSE Handler
    handler := sse.NewHandler(nil)

    // 路由挂载
    http.Handle("/sse/", handler)
    http.Handle("/api/", handler)

    fmt.Println("SSE Server started on :8080")
    http.ListenAndServe(":8080", nil)
}
Client (客户端)
package main

import (
    "context"
    "fmt"

    "gitee.com/vipkwds/sse"
)

func main() {
    ctx := context.Background()

    // 创建 SSE 客户端
    client := sse.NewSSEClient("http://localhost:8080/sse/user123",
        sse.WithSSEClientOnMessage(func(data []byte) {
            fmt.Printf("收到消息: %s\n", data)
        }),
        sse.WithSSEClientOnConnect(func() {
            fmt.Println("已连接服务器")
        }),
    )

    // 连接
    if err := client.Connect(ctx); err != nil {
        panic(err)
    }

    // 保持运行
    select {}
}

API 参考

Handler (推荐方式)
// 创建 Handler
handler := sse.NewHandler(nil)

// 自定义配置
handler := sse.NewHandler(nil,
    sse.WithStorage(sse.NewMemoryStorage(1024)),
    sse.WithConfig(&sse.HandlerConfig{
        HistoryDuration: 5 * time.Minute,
        CleanupInterval: 1 * time.Minute,
    }),
)

// 挂载到路由
http.Handle("/sse/", handler)  // GET /sse/*clientId
http.Handle("/api/", handler) // JSON API

// 直接操作
handler.SendToClient("client1", "event", data)
handler.Broadcast("notice", map[string]string{"msg": "hello"})
handler.JoinRoom("client1", "room1")
handler.Shutdown()
Hub (底层接口)
hub := sse.NewHub(nil)

// 注册客户端
client := hub.NewClient("client-id", metadata)
hub.Register(client)

// 发送消息
hub.SendToClient("client-id", "event", data)
hub.SendToRoom("room-name", "event", data)
hub.Broadcast("event", data, exclude...)

// 房间管理
hub.JoinRoom("client-id", "room-name")
hub.LeaveRoom("client-id", "room-name")

// 统计
stats := hub.GetStats()
fmt.Printf("Clients: %d, Rooms: %d\n", stats.TotalClients, stats.TotalRooms)

// 优雅关闭
hub.Shutdown()
SSEClient (Go 客户端)
client := sse.NewSSEClient("http://localhost:8080/sse/user123",
    // 自定义请求头
    sse.WithSSEClientHeader("Authorization", "Bearer token"),
    // 最大重试次数 (默认 10)
    sse.WithSSEClientMaxRetry(5),
    // 重连间隔 (默认 3秒)
    sse.WithSSEClientReconnect(5 * time.Second),
    // 开启客户端回复 ack(留空则自动从 SSE URL 推导 ack 地址)
    sse.WithClientAck(""),
    // 消息回调
    sse.WithSSEClientOnMessage(func(event string, data []byte) {
        fmt.Printf("收到事件 %s: %s\n", event, data)
    }),
    // 连接成功回调
    sse.WithSSEClientOnConnect(func() { ... }),
    // 断开连接回调
    sse.WithSSEClientOnDisconnect(func() { ... }),
    // 错误回调
    sse.WithSSEClientOnError(func(err error) { ... }),
)

// 连接
client.Connect(ctx)

// 发送消息 (通过 HTTP POST)
client.SendMessage(ctx, "/api/send", map[string]any{
    "clientId": "user123",
    "event":   "message",
    "data":    map[string]string{"text": "hello"},
})

// 获取最后的 Event ID (用于重连)
lastID := client.LastEventID()

// 关闭
client.Close()
Storage 接口 (自定义存储)
type Storage interface {
    // 保存消息
    Save(msg *Message)
    // 遍历指定时间戳之后的消息
    RangeSince(clientID string, since int64, fn func(msg *Message) bool)
    // 清理过期消息
    Cleanup(maxAge time.Duration)
}

// 使用自定义存储
type RedisStorage struct { ... }

func (s *RedisStorage) Save(msg *sse.Message) { ... }
func (s *RedisStorage) RangeSince(clientID string, since int64, fn func(msg *sse.Message) bool) bool { ... }
func (s *RedisStorage) Cleanup(maxAge time.Duration) { ... }

handler := sse.NewHandler(nil, sse.WithStorage(&RedisStorage{...}))

JSON API (内置)

Handler 挂载到 /api/ 时自动提供以下接口:

端点 方法 说明
/api/stats GET 获取连接统计
/api/send POST 发送消息给客户端
/api/broadcast POST 广播消息
/api/room/send POST 发送消息到房间
/api/room/join POST 加入房间
/api/room/leave POST 离开房间
/api/ack POST 处理客户端心跳应答
示例
# 发送消息
curl -X POST http://localhost:8080/api/send \
  -H "Content-Type: application/json" \
  -d '{"clientId":"user123","event":"message","data":{"text":"Hello!"}}'

# 广播
curl -X POST http://localhost:8080/api/broadcast \
  -H "Content-Type: application/json" \
  -d '{"event":"notice","data":{"msg":"System announcement"}}'

# 加入房间
curl -X POST http://localhost:8080/api/room/join \
  -H "Content-Type: application/json" \
  -d '{"clientId":"user123","room":"room1"}'

重连机制

服务端

服务端自动维护消息历史(新消息补发):

  • 客户端断开时,服务端保留消息历史(默认 5 分钟)
  • 客户端重连时,自动发送 Last-Event-ID 请求头
  • 服务端根据时间戳自动补发断线期间的消息
客户端

客户端自动重连:

  • 连接失败时,自动根据 reconnect 间隔重试
  • maxRetry 次重试后放弃
  • 重连时自动携带上次的 Last-Event-ID
client := sse.NewSSEClient("http://localhost:8080/sse/user123",
    sse.WithSSEClientReconnect(3 * time.Second),
    sse.WithSSEClientMaxRetry(10),
)

双向心跳保活

双向心跳保活需要 Server 和 Client 两端同时开启。

服务端配置
hub := sse.NewHub(&sse.Config{
    HeartbeatInterval: 30,   // Server→Client 心跳间隔(秒,0=关闭)
    ClientAckTimeout:  10,    // Client ack 超时阈值(秒,0=关闭双向保活)
    ClientAckMaxTimes: 3,     // 连续超时次数超限则强制断开
})
客户端配置
client := sse.NewSSEClient("http://localhost:8080/sse/user123",
    // 开启 Client ack 回写(留空则自动从 SSE URL 推导)
    sse.WithClientAck("http://localhost:8080/api/ack"),
)
交互流程
  1. Server 每 HeartbeatInterval 秒向所有 Client 发送 event: _heartbeat 心跳
  2. Client 收到心跳后解析 JSON 中的 time 字段,自动 POST ack 到 /api/ack
  3. Server 每 5 秒检查一次 Client 最后 ack 时间
  4. 若距上次 ack 超时 ClientAckTimeout 秒,计数 +1
  5. 累计超 ClientAckMaxTimes 次,强制断开该 Client
Storage 要求

双向心跳保活要求 Storage 实现以下三个方法(未实现则自动关闭):

type Storage interface {
    // ... 基础方法 ...
    SetClientAck(clientID string, ts int64) error
    GetClientAck(clientID string) (int64, error)
    DelClientAck(clientID string) error
}

MemoryStorage 默认实现了这三个方法。自定义存储只需实现对应方法即可无缝接入。

消息 ID 格式

消息 ID 格式: {uuid}-{timestamp}

示例: 550e8400-e29b-41d4-a716-446655440000-1609459200000

  • UUID - 唯一标识
  • Timestamp - 毫秒时间戳,可用于判断消息时效

SSE 协议格式

id: <message-id>
event: <event-type>
data: <payload>

完整示例

双向通信示例
package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    "gitee.com/vipkwds/sse"
)

func main() {
    ctx := context.Background()

    // 1. 启动 SSE Server
    handler := sse.NewHandler(nil)

    http.Handle("/sse/", handler)
    http.Handle("/api/", handler)

    go func() {
        fmt.Println("Server started on :8080")
        log.Fatal(http.ListenAndServe(":8080", nil))
    }()

    // 2. 启动 SSE Client
    client := sse.NewSSEClient("http://localhost:8080/sse/user123",
        sse.WithSSEClientOnMessage(func(data []byte) {
            fmt.Printf("客户端收到: %s\n", data)
        }),
        sse.WithSSEClientOnConnect(func() {
            fmt.Println("客户端已连接")
        }),
    )

    if err := client.Connect(ctx); err != nil {
        panic(err)
    }

    // 3. Server 广播消息
    time.Sleep(100 * time.Millisecond)
    handler.Broadcast("notice", map[string]string{
        "msg": "Hello from Server!",
    })

    // 4. Client 发送消息
    time.Sleep(100 * time.Millisecond)
    client.SendMessage(ctx, "/api/send", map[string]any{
        "clientId": "user123",
        "event":   "message",
        "data":    map[string]string{"text": "Hello from Client!"},
    })

    // 5. 等待中断信号
    sig := make(chan os.Signal, 1)
    signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
    <-sig

    // 6. 清理
    client.Close()
    handler.Shutdown()
    fmt.Println("已退出")
}
房间聊天示例
// 加入房间
handler.JoinRoom("user1", "room-general")

// 向房间发送消息
handler.SendToRoom("room-general", "message", map[string]string{
    "user":    "user1",
    "content": "Hello everyone!",
})

// 离开房间
handler.LeaveRoom("user1", "room-general")

配置项

HandlerConfig
type HandlerConfig struct {
    // 消息历史保留时间 (默认 5 分钟)
    HistoryDuration time.Duration
    // 历史清理间隔 (默认 1 分钟)
    CleanupInterval time.Duration
    // 连接超时 (默认 30 秒)
    ConnectTimeout time.Duration
}
Config (Hub)
type Config struct {
    // 心跳间隔秒数 (默认 30,0=关闭)
    HeartbeatInterval int
    // Client ack 超时秒数 (默认 0=关闭双向保活)
    ClientAckTimeout  int
    // 连续 ack 超时多少次后主动断开 (默认 3)
    ClientAckMaxTimes int
    // 消息缓冲区大小 (默认 256)
    MessageBufferSize int
    // 是否启用日志 (默认 true)
    EnableLog bool
}

项目结构

sse/
├── sse.go          # Hub + Client (Server端核心)
├── history.go      # Storage 接口 + MemoryStorage
├── handler.go      # HTTP Handler (开箱即用)
├── client.go       # SSE Client (纯 Go 客户端)
└── *_test.go       # 测试文件

依赖

  • github.com/google/uuid (生成消息 ID)

许可证

MIT

Documentation

Overview

client.go

handler.go

history.go

sse/sse.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BeforeWrite

type BeforeWrite func(wf WriteFlusher)

BeforeWrite 在每次 w.Write 之前调用,用于框架特定的 flush 操作 wf 是实现了 WriteFlusher 接口的原始 ResponseWriter

type Client

type Client struct {
	ID          string
	LastEventID string // 客户端上次收到的消息 ID(重连时从请求头获取)
	Send        chan []byte
	Hub         *Hub
	Metadata    map[string]interface{}
	// contains filtered or unexported fields
}

Client 客户端连接

func (*Client) Close

func (c *Client) Close()

Close 关闭客户端

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done 返回关闭通道

func (*Client) SendMessage

func (c *Client) SendMessage(event string, data []byte)

SendMessage 发送消息

type Config

type Config struct {
	HeartbeatInterval int // Server→Client 心跳间隔秒数(0=关闭,默认30秒)

	//  --- todo: 请求栈有bug,暂不开启 2026-05-30
	ClientAckTimeout  int // Client ack 超时秒数(默认0=关闭双向保活)
	ClientAckMaxTimes int // 连续失败多少次后主动断开(0=默认3次)
	MessageBufferSize int
	EnableLog         bool
}

Config 配置

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 默认配置

type Handler

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

Handler SSE HTTP 处理器(可路由挂载)

func NewHandler

func NewHandler(hub *Hub, opts ...Option) *Handler

NewHandler 创建 SSE Handler

func (*Handler) API

func (h *Handler) API() http.HandlerFunc

API Handler(JSON API)

func (*Handler) Broadcast

func (h *Handler) Broadcast(event string, data any, exclude ...string)

Broadcast 广播消息

func (*Handler) ClientHandler

func (h *Handler) ClientHandler(clientID string) http.HandlerFunc

ClientHandler 返回客户端用 SSE Handler(带自动重连)

func (*Handler) Handle

func (h *Handler) Handle() http.HandlerFunc

Handle HTTP HandlerFunc

func (*Handler) Hub

func (h *Handler) Hub() *Hub

Hub 返回底层 Hub(供外部发送消息用)

func (*Handler) JoinRoom

func (h *Handler) JoinRoom(clientID, room string)

JoinRoom 加入房间

func (*Handler) LeaveRoom

func (h *Handler) LeaveRoom(clientID, room string)

LeaveRoom 离开房间

func (*Handler) SendToClient

func (h *Handler) SendToClient(clientID, event string, data any) error

SendToClient 发送消息给客户端

func (*Handler) ServeHTTP

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

ServeHTTP 实现 http.Handler 接口

func (*Handler) Shutdown

func (h *Handler) Shutdown()

Shutdown 关闭

type HandlerConfig

type HandlerConfig struct {
	// 消息历史保留时间(默认 5 分钟)
	HistoryDuration time.Duration
	// 历史清理间隔(默认 1 分钟)
	CleanupInterval time.Duration
	// 初始连接超时
	ConnectTimeout time.Duration
}

func DefaultHandlerConfig

func DefaultHandlerConfig() *HandlerConfig

type Hub

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

Hub 连接管理中心

func NewHub

func NewHub(config *Config) *Hub

NewHub 创建 Hub

func (*Hub) Broadcast

func (h *Hub) Broadcast(event string, data interface{}, exclude ...string)

Broadcast 广播给所有

func (*Hub) GetStats

func (h *Hub) GetStats() Stats

GetStats 获取统计信息

func (*Hub) HandleClientAck

func (h *Hub) HandleClientAck(clientID string, beatTime int64) error

HandleClientAck 处理 client 发来的 ack

func (*Hub) JoinRoom

func (h *Hub) JoinRoom(clientID, room string)

JoinRoom 客户端加入房间

func (*Hub) LeaveRoom

func (h *Hub) LeaveRoom(clientID, room string)

LeaveRoom 离开房间

func (*Hub) NewClient

func (h *Hub) NewClient(id string, metadata map[string]interface{}) *Client

NewClient 创建客户端

func (*Hub) Register

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

Register 注册客户端

func (*Hub) SendToClient

func (h *Hub) SendToClient(clientID string, event string, data interface{}) error

SendToClient 发送给指定客户端

func (*Hub) SendToRoom

func (h *Hub) SendToRoom(room string, event string, data interface{}, exclude ...string)

SendToRoom 发送给房间

func (*Hub) SetStorage

func (h *Hub) SetStorage(s Storage)

SetStorage 设置 storage(供 Handler 使用同一个 storage)

func (*Hub) Shutdown

func (h *Hub) Shutdown()

Shutdown 优雅关闭 Hub

type MemoryStorage

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

MemoryStorage 内存存储(环形缓冲)

func NewMemoryStorage

func NewMemoryStorage(cap int) *MemoryStorage

func (*MemoryStorage) Cleanup

func (s *MemoryStorage) Cleanup(maxAge time.Duration)

func (*MemoryStorage) DelClientAck

func (s *MemoryStorage) DelClientAck(clientID string) error

DelClientAck 删除客户端 ack 记录

func (*MemoryStorage) GetClientAck

func (s *MemoryStorage) GetClientAck(clientID string) (int64, error)

GetClientAck 获取客户端最后 ack 时间

func (*MemoryStorage) RangeSince

func (s *MemoryStorage) RangeSince(clientID string, since int64, fn func(msg *Message) bool)

func (*MemoryStorage) Save

func (s *MemoryStorage) Save(msg *Message)

func (*MemoryStorage) SetClientAck

func (s *MemoryStorage) SetClientAck(clientID string, ts int64) error

SetClientAck 设置客户端最后 ack 时间

type Message

type Message struct {
	ID        string
	Event     string
	Data      []byte
	Timestamp time.Time
	ClientID  string // 发送目标(空=广播)
	IsSystem  bool   // 是否系统消息(heartbeat等,不存入历史)
}

Message 存储的消息结构

type OnClientConnect

type OnClientConnect func(clientID string)

OnClientConnect 客户端连接成功时的回调(可选) 参数为 clientID,可用于向该 client 发送初始数据

type Option

type Option func(*Handler)

func WithBeforeWrite

func WithBeforeWrite(fn BeforeWrite) Option

WithBeforeWrite 设置每次 w.Write 之前的回调,用于框架特定的 flush 操作 beego 用户示例:sse.WithBeforeWrite(func(wf sse.WriteFlusher) { wf.Flush() })

func WithConfig

func WithConfig(cfg *HandlerConfig) Option

func WithOnClientConnect

func WithOnClientConnect(fn OnClientConnect) Option

WithOnClientConnect 设置客户端连接成功时的回调 可用于向新连接的客户端发送初始数据(如配置同步)

func WithRequestMutator

func WithRequestMutator(fn RequestMutator) Option

WithRequestMutator 设置请求预处理函数,用于 path 重写等框架适配

func WithStorage

func WithStorage(s Storage) Option

type RequestMutator

type RequestMutator func(r *http.Request)

RequestMutator 请求预处理函数,用于 path 重写等框架适配

type SSEClient

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

SSEClient SSE 客户端

func NewSSEClient

func NewSSEClient(url string, opts ...SSEClientOption) *SSEClient

NewSSEClient 创建 SSE 客户端

func (*SSEClient) Close

func (c *SSEClient) Close() error

Close 关闭连接

func (*SSEClient) Connect

func (c *SSEClient) Connect(ctx context.Context) error

Connect 连接 SSE 服务器

func (*SSEClient) LastEventID

func (c *SSEClient) LastEventID() string

LastEventID 获取最后的 Event ID

func (*SSEClient) SendMessage

func (c *SSEClient) SendMessage(ctx context.Context, path string, data any) error

SendMessage 通过 HTTP POST 发送消息

type SSEClientOption

type SSEClientOption func(*SSEClient)

func WithClientAck

func WithClientAck(ackURL string) SSEClientOption

WithClientAck 开启客户端回复 ack(收到 server 心跳后自动回 ack)

func WithSSEClientHeader

func WithSSEClientHeader(key, val string) SSEClientOption

func WithSSEClientMaxRetry

func WithSSEClientMaxRetry(n int) SSEClientOption

sseClient断线重连接机制:0表示不重试 -1表示无限重试

func WithSSEClientOnConnect

func WithSSEClientOnConnect(fn func()) SSEClientOption

func WithSSEClientOnDisconnect

func WithSSEClientOnDisconnect(fn func()) SSEClientOption

func WithSSEClientOnError

func WithSSEClientOnError(fn func(error)) SSEClientOption

func WithSSEClientOnMessage

func WithSSEClientOnMessage(fn func(event string, data []byte)) SSEClientOption

func WithSSEClientReconnect

func WithSSEClientReconnect(d time.Duration) SSEClientOption

type Stats

type Stats struct {
	TotalClients int      `json:"total_clients"`
	TotalRooms   int      `json:"total_rooms"`
	RoomNames    []string `json:"room_names"`
}

Stats Hub 统计信息

type Storage

type Storage interface {
	// Save 保存消息
	Save(msg *Message)
	// Range 遍历指定时间戳之后的消息
	RangeSince(clientID string, since int64, fn func(msg *Message) bool)
	// Cleanup 清理过期消息
	Cleanup(maxAge time.Duration)

	// 以下三个方法是可选实现,未实现则双向保活不生效
	// SetClientAck 设置客户端最后 ack 时间
	SetClientAck(clientID string, ts int64) error
	// GetClientAck 获取客户端最后 ack 时间
	GetClientAck(clientID string) (int64, error)
	// DelClientAck 删除客户端 ack 记录
	DelClientAck(clientID string) error
}

Storage 消息存储接口(插拔式)

type WriteFlusher

type WriteFlusher interface {
	http.ResponseWriter
	http.Flusher
	CloseNotify() <-chan bool
}

WriteFlusher 组合了标准库的 http.ResponseWriter, http.Flusher, http.CloseNotifier 用于 SSE 流式响应,让外部框架可以直接拿到原始 Writer 进行 flush 操作

Jump to

Keyboard shortcuts

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