Documentation
¶
Overview ¶
Application scenarios: - Define the framework-agnostic HTTP request context contract. - Let provider adapters implement this interface by delegating to concrete HTTP frameworks. - Keep routing, binding, response output, and request metadata access consistent across providers.
适用场景: - 定义与具体框架无关的 HTTP 请求上下文契约。 - 让 provider 适配层通过委托模式实现此接口。 - 在不同 provider 之间统一路由、绑定、响应输出和请求元数据访问语义。
Application scenarios: - Define transport-layer gRPC connection and server registration contracts. - Keep gRPC client/server assembly provider-neutral at the transport contract layer. - Let application and container helpers fetch gRPC capabilities through stable keys.
适用场景: - 定义 transport 层 gRPC 连接与服务端注册契约。 - 在 transport 契约层保持 gRPC 客户端/服务端装配与 provider 解耦。 - 让 application 和 container helper 通过稳定 key 获取 gRPC 能力。
Application scenarios: - Define the transport-layer HTTP service contract shared by providers and bootstrap logic. - Keep router access, server access, run, and shutdown semantics stable. - Let application code depend on one HTTP abstraction instead of a concrete framework.
适用场景: - 定义 provider 和 bootstrap 共同使用的 transport 层 HTTP 服务契约。 - 稳定维护路由访问、server 访问、运行和关闭语义。 - 让应用代码依赖统一 HTTP 抽象,而不是具体框架实现。
Application scenarios: - Define the framework-wide HTTP responder contract used by middleware and handlers. - Separate transport-layer response writing from business handler logic. - Keep success/error response shaping replaceable across providers and applications.
适用场景: - 定义中间件和处理器共同使用的框架级 HTTP responder 契约。 - 将 transport 层响应写出逻辑与业务 handler 解耦。 - 让成功/失败响应整形能力可以在 provider 和应用之间替换。
Application scenarios: - Define transport-level metadata propagation contracts for HTTP and RPC flows. - Provide a reusable in-memory metadata implementation with cloning and context propagation helpers. - Keep metadata access, injection, and extraction semantics uniform across providers.
适用场景: - 定义 HTTP 和 RPC 流程共享的 transport 层 metadata 透传契约。 - 提供一个可复用的内存 metadata 实现,以及克隆和 context 透传助手。 - 在不同 provider 之间统一 metadata 的访问、注入和提取语义。
Application scenarios:
- Define the middleware registry contract for proto-annotation-driven automatic middleware mounting.
- Allow users to register named middleware instances (e.g., "auth", "logging") and have the generated route code automatically look them up by name.
- Decouple proto declaration from middleware implementation: proto says "auth: true", the registry maps "auth" to the actual middleware instance.
适用场景:
- 定义 proto 注解驱动的自动中间件挂载所需的注册表契约。
- 允许用户注册具名中间件实例(如 "auth"、"logging"), 生成的路由代码按名称自动查找对应中间件。
- 解耦 proto 声明与中间件实现:proto 声明 "auth: true", 注册表将 "auth" 映射到实际的中间件实例。
Application scenarios: - Define the framework-agnostic HTTP router contract. - Let provider adapters expose route registration and middleware composition through one shared shape. - Keep business route declaration independent from Gin or other concrete router implementations.
适用场景: - 定义与具体框架无关的 HTTP 路由契约。 - 让 provider 适配层通过统一形态暴露路由注册与中间件组合能力。 - 让业务路由声明不依赖 Gin 或其他具体路由实现。
Application scenarios: - Define transport-layer RPC contracts shared by providers and higher-level runtime code. - Keep client, server, and registry semantics provider-neutral across HTTP and gRPC style transports. - Provide a shared config model for RPC mode, target, registry, and timeout settings.
适用场景: - 定义 provider 与上层运行时代码共享的 transport 层 RPC 契约。 - 在 HTTP、gRPC 等不同传输模式下保持客户端、服务端和注册中心语义的 provider 中立。 - 为 RPC 模式、目标地址、注册中心和超时设置提供共享配置模型。
Package transport defines transport-layer contracts for gorp framework. This file defines the WebSocket abstraction contract.
Transport 包定义 gorp 框架的传输层契约。 本文件定义 WebSocket 抽象契约。
Index ¶
- Constants
- func AppendToClientContext(ctx context.Context, kv ...string) context.Context
- func NewClientContext(ctx context.Context, md Metadata) context.Context
- func NewServerContext(ctx context.Context, md Metadata) context.Context
- type BindingContext
- type Context
- type GINEngineProvider
- type GRPCConnFactory
- type GRPCServerRegistrar
- type HTTP
- type HTTPResponder
- type Handler
- type Metadata
- type MetadataCarrier
- type MetadataConfig
- type MetadataPropagator
- type Middleware
- type MiddlewareContext
- type MiddlewareFunc
- type MiddlewareRegistry
- type RPCClient
- type RPCClientMiddleware
- type RPCConfig
- type RPCInvoker
- type RPCServer
- type RequestContext
- type ResponseContext
- type RouteContext
- type Router
- type ServiceInstance
- type ServiceRegistry
- type WebSocketBroadcaster
- type WebSocketClient
- type WebSocketClientConfig
- type WebSocketClusterConfig
- type WebSocketClusterServer
- type WebSocketConfig
- type WebSocketConn
- type WebSocketHandler
- type WebSocketServer
Constants ¶
const ( GRPCConnFactoryKey = "framework.grpc.conn_factory" GRPCServerRegistrarKey = "framework.grpc.server_registrar" )
const ( MetadataKey = "framework.metadata" MetadataPropagatorKey = "framework.metadata.propagator" )
const ( RPCClientKey = "framework.rpc.client" RPCServerKey = "framework.rpc.server" RPCRegistryKey = "framework.rpc.registry" )
const HTTPKey = "framework.http"
HTTPKey is the container key for the HTTP service capability.
HTTPKey 是 HTTP 服务能力的容器键。
const HTTPResponderKey = "framework.http.responder"
HTTPResponderKey is the container key for the HTTP responder capability.
HTTPResponderKey 是 HTTP responder 能力的容器键。
const MiddlewareRegistryKey = "framework.http.middleware_registry"
MiddlewareRegistryKey is the container key for the middleware registry.
MiddlewareRegistryKey 是中间件注册表的容器键。
const WebSocketKey = "framework.transport.websocket"
WebSocketKey is the container key for WebSocket service.
WebSocketKey 是 WebSocket 服务的容器键。
Variables ¶
This section is empty.
Functions ¶
func AppendToClientContext ¶
AppendToClientContext appends metadata key-value pairs into a client context.
AppendToClientContext 向客户端 context 追加 metadata 键值对。
func NewClientContext ¶
NewClientContext attaches client-side metadata into a context.
NewClientContext 将客户端 metadata 绑定到 context。
Types ¶
type BindingContext ¶
type BindingContext interface {
Bind(obj any) error
BindJSON(obj any) error
BindQuery(obj any) error
}
BindingContext 提供请求绑定能力。 用于需要解析请求体的 Handler。
type Context ¶
type Context interface {
RequestContext
BindingContext
ResponseContext
MiddlewareContext
RouteContext
}
Context is the aggregate interface composing all sub-interfaces. It provides the full HTTP request context abstraction. Providers implement this interface by delegating to their underlying context.
Context 是聚合接口,组合所有子接口。 提供完整的 HTTP 请求上下文抽象。 Provider 通过委托到底层 context 实现此接口。
type GINEngineProvider ¶
type GINEngineProvider interface {
GINEngine() any
}
GINEngineProvider is an optional interface that HTTP implementations can satisfy to expose the underlying *gin.Engine for Gin-first usage. When the HTTP service is backed by Gin, callers can type-assert to this interface to access native Gin capabilities.
GINEngineProvider 是 HTTP 实现可满足的可选接口,用于暴露底层 *gin.Engine 供 Gin-first 使用。 当 HTTP 服务由 Gin 驱动时,调用方可通过类型断言访问原生 Gin 能力。
type GRPCConnFactory ¶
type GRPCConnFactory interface {
// Conn returns the client connection of the target service.
//
// Conn 返回目标服务的客户端连接。
Conn(ctx context.Context, service string) (*grpc.ClientConn, error)
}
GRPCConnFactory resolves outbound gRPC connections by service name.
GRPCConnFactory 按服务名解析出站 gRPC 连接。
type GRPCServerRegistrar ¶
type GRPCServerRegistrar interface {
// RegisterProto registers a proto service against the underlying gRPC server.
//
// RegisterProto 将 proto 服务注册到底层 gRPC server 上。
RegisterProto(func(server *grpc.Server) error) error
// Server returns the underlying gRPC server.
//
// Server 返回底层 gRPC server。
Server() *grpc.Server
}
GRPCServerRegistrar registers proto services onto a gRPC server.
GRPCServerRegistrar 定义将 proto 服务注册到 gRPC server 的能力。
type HTTP ¶
type HTTP interface {
// Router returns the framework HTTP router facade.
//
// Router 返回框架 HTTP 路由门面。
Router() Router
// Server returns the underlying net/http server.
//
// Server 返回底层 net/http server。
Server() *http.Server
// Run starts serving HTTP traffic.
//
// Run 启动 HTTP 流量服务。
Run() error
// Shutdown gracefully stops the HTTP service.
//
// Shutdown 优雅关闭 HTTP 服务。
Shutdown(ctx context.Context) error
// UseGlobal 注册全局级中间件,对所有路由生效。
// 语义等同于 Gin 的 engine.Use(),区别于 Router.Use() 的组级语义。
// 全局中间件在框架治理中间件之后、路由组中间件之前执行。
//
// UseGlobal registers global-level middleware that applies to all routes.
// Semantically equivalent to Gin's engine.Use(), distinct from Router.Use() which is group-level.
// Global middleware executes after framework governance middleware and before group-level middleware.
UseGlobal(middleware ...Middleware)
}
HTTP defines the transport-layer HTTP service abstraction.
HTTP 定义 transport 层 HTTP 服务抽象。
type HTTPResponder ¶
type HTTPResponder interface {
Success(Context, any)
SuccessWithMessage(Context, string, any)
SuccessWithStatus(Context, int, any)
Error(Context, error)
BadRequest(Context, string)
InternalError(Context, string)
}
HTTPResponder defines the response-writing contract used by the framework.
HTTPResponder 定义框架使用的响应写出契约。
type Handler ¶
type Handler func(Context)
Handler defines the HTTP handler signature.
Handler 定义 HTTP 处理器签名。
type Metadata ¶
type Metadata interface {
Get(key string) string
Values(key string) []string
Set(key, value string)
Add(key, value string)
Del(key string)
Range(f func(key string, values []string) bool)
Clone() Metadata
ToMap() map[string][]string
}
Metadata defines the transport metadata abstraction.
Metadata 定义 transport metadata 抽象。
func FromClientContext ¶
FromClientContext reads client-side metadata from a context.
FromClientContext 从 context 中读取客户端 metadata。
func FromServerContext ¶
FromServerContext reads server-side metadata from a context.
FromServerContext 从 context 中读取服务端 metadata。
func NewMetadata ¶
func NewMetadata() Metadata
NewMetadata creates an empty in-memory metadata implementation.
NewMetadata 创建一个空的内存 metadata 实现。
func NewMetadataFromMap ¶
NewMetadataFromMap creates an in-memory metadata object from a map snapshot.
NewMetadataFromMap 从 map 快照创建内存 metadata 对象。
type MetadataCarrier ¶
type MetadataCarrier interface {
Get(key string) string
Set(key, value string)
Add(key, value string)
Keys() []string
Values(key string) []string
}
MetadataCarrier defines the read/write carrier abstraction used during propagation.
MetadataCarrier 定义透传过程中使用的读写载体抽象。
type MetadataConfig ¶
type MetadataConfig struct {
PropagatePrefix []string `mapstructure:"propagate_prefix"`
ConstantMetadata map[string]string `mapstructure:"constant_metadata"`
MaxSize int `mapstructure:"max_size"`
}
MetadataConfig describes metadata propagation behavior.
MetadataConfig 描述 metadata 透传配置。
type MetadataPropagator ¶
type MetadataPropagator interface {
Inject(ctx context.Context, carrier MetadataCarrier)
Extract(ctx context.Context, carrier MetadataCarrier) context.Context
}
MetadataPropagator defines how metadata should be injected and extracted.
MetadataPropagator 定义 metadata 的注入与提取方式。
type MiddlewareContext ¶
type MiddlewareContext interface {
Get(key string) (any, bool)
Set(key string, value any)
Abort(status int)
AbortWithJSON(status int, body any)
IsAborted() bool
Next()
}
MiddlewareContext 提供中间件控制流能力。 用于中间件实现。 Get 返回 (value, exists),与 Gin 原生语义对齐, 可区分"key 不存在"和"key 存在但值为 nil"。
type MiddlewareFunc ¶
MiddlewareFunc is a business-friendly helper signature used by Middleware.
MiddlewareFunc 是 Middleware 使用的业务友好辅助签名。
type MiddlewareRegistry ¶
type MiddlewareRegistry interface {
// Register adds a named middleware to the registry.
// If a middleware with the same name already exists, it is replaced.
// Common names: "auth", "authz", "logging", "ratelimit", "cors".
//
// Register 向注册表添加具名中间件。
// 如果同名中间件已存在,则替换。
// 常用名称:"auth"、"authz"、"logging"、"ratelimit"、"cors"。
Register(name string, middleware Middleware)
// Lookup retrieves a middleware by name.
// Returns the middleware and true if found, nil and false otherwise.
//
// Lookup 按名称查找中间件。
// 找到时返回中间件和 true,否则返回 nil 和 false。
Lookup(name string) (Middleware, bool)
// LookupAll retrieves multiple middleware by names.
// Returns found middleware in order; silently skips unknown names.
//
// LookupAll 按名称列表查找多个中间件。
// 按顺序返回找到的中间件;静默跳过未知名称。
LookupAll(names []string) []Middleware
// Names returns all registered middleware names.
//
// Names 返回所有已注册的中间件名称。
Names() []string
}
MiddlewareRegistry defines the contract for named middleware registration and lookup. Proto annotations (gorp.auth, gorp.middleware) reference middleware by name; the registry maps names to concrete Middleware instances.
MiddlewareRegistry 定义具名中间件注册与查找契约。 Proto 注解(gorp.auth、gorp.middleware)通过名称引用中间件; 注册表将名称映射到具体的 Middleware 实例。
中文说明: - 用户在应用启动时注册中间件:registry.Register("auth", jwtAuthMiddleware) - proto 声明 (gorp.auth) = { required: true },生成代码调用 registry.Lookup("auth") - 注册表解耦了 proto 声明与具体中间件实现,同一套 proto 可在不同项目中使用不同中间件
type RPCClient ¶
type RPCClient interface {
Call(ctx context.Context, service, method string, req, resp any) error
CallRaw(ctx context.Context, service, method string, data []byte) ([]byte, error)
Close() error
}
RPCClient defines the outbound RPC client contract.
RPCClient 定义出站 RPC 客户端契约。
type RPCClientMiddleware ¶
type RPCClientMiddleware func(next RPCInvoker) RPCInvoker
RPCClientMiddleware defines one outbound RPC governance middleware.
RPCClientMiddleware 定义一个出站 RPC 治理中间件。
type RPCConfig ¶
type RPCConfig struct {
Mode string `mapstructure:"mode"`
Registry string `mapstructure:"registry"`
Address string `mapstructure:"address"`
BaseURL string `mapstructure:"base_url"`
Target string `mapstructure:"target"`
Insecure bool `mapstructure:"insecure"`
TimeoutMS int `mapstructure:"timeout_ms"`
}
RPCConfig describes RPC-related runtime configuration.
RPCConfig 描述 RPC 相关运行时配置。
type RPCInvoker ¶
RPCInvoker defines one outbound RPC invocation function.
RPCInvoker 定义一次出站 RPC 调用函数。
type RPCServer ¶
type RPCServer interface {
Register(service string, handler any) error
Start(ctx context.Context) error
Stop(ctx context.Context) error
Addr() string
}
RPCServer defines the inbound RPC server contract.
RPCServer 定义入站 RPC 服务端契约。
type RequestContext ¶
type RequestContext interface {
// Context 返回标准 context.Context。
// 用于 context.WithTimeout/context.WithCancel/context.WithValue 等场景。
// 实现层应返回 Request().Context(),确保只返回纯标准 context,不再回包到 RequestContext。
Context() context.Context
// Request/Response
Request() *http.Request
Response() http.ResponseWriter
// Route params
Param(key string) string
// Query params
Query(key string) string
DefaultQuery(key, defaultValue string) string
DefaultIntQuery(key string, defaultValue int) int
// Typed param parsing
Int64Param(key string) (int64, error)
// File upload
FormFile(name string) (multipart.File, *multipart.FileHeader, error)
SaveUploadedFile(file *multipart.FileHeader, dst string) error
// Headers
GetHeader(key string) string
SetHeader(key, value string)
}
RequestContext 提供请求元数据访问。 注意:与 context.Context 解耦 —— 业务/中间件如需获取标准 context.Context, 必须通过 c.Context() 方法显式获取,禁止把 RequestContext 直接当作 context.Context 使用。 这样做的根本原因:若直接嵌入 context.Context,provider 实现(如 ginContext)会与 Request().Context() 形成双向引用,标准库遍历 valueCtx 链时触发无限递归导致栈溢出。 详见 docs/design/bug-list.md BUG-001。
type ResponseContext ¶
type ResponseContext interface {
JSON(status int, body any)
String(status int, body string)
XML(status int, body any)
Data(status int, contentType string, body []byte)
Redirect(status int, location string)
Status(code int)
}
ResponseContext 提供响应输出能力。 用于需要返回响应的 Handler。
type RouteContext ¶
RouteContext 提供路由信息访问。 用于需要知道当前路由信息的场景。
type Router ¶
type Router interface {
Use(middleware ...Middleware)
Group(prefix string, middleware ...Middleware) Router
// Handle 为指定 method 和 path 注册路由处理器,可选挂载接口级中间件。
// middleware 只对该路由端点生效,不影响其他路由。
//
// Handle registers a route handler for the given method and path,
// with optional interface-level middleware that applies only to this route.
Handle(method, path string, handler Handler, middleware ...Middleware)
// HandleFunc 是 Handle 的函数式别名,支持可选接口级中间件。
//
// HandleFunc is a function-style alias for Handle with optional interface-level middleware.
HandleFunc(method, path string, handlerFunc Handler, middleware ...Middleware)
// GET 注册 GET 路由处理器,可选挂载接口级中间件。
// 示例:GET("/users", listUsers) 或 GET("/users", listUsers, authMW)
//
// GET registers a GET route handler with optional interface-level middleware.
GET(path string, handler Handler, middleware ...Middleware)
// POST 注册 POST 路由处理器,可选挂载接口级中间件。
//
// POST registers a POST route handler with optional interface-level middleware.
POST(path string, handler Handler, middleware ...Middleware)
// PUT 注册 PUT 路由处理器,可选挂载接口级中间件。
//
// PUT registers a PUT route handler with optional interface-level middleware.
PUT(path string, handler Handler, middleware ...Middleware)
// DELETE 注册 DELETE 路由处理器,可选挂载接口级中间件。
//
// DELETE registers a DELETE route handler with optional interface-level middleware.
DELETE(path string, handler Handler, middleware ...Middleware)
Mount(path string, handler http.Handler)
}
Router defines the HTTP router abstraction.
Router 定义 HTTP 路由抽象。
路由注册方法支持接口级中间件:
- 不传 middleware 时行为与原来一致:GET("/users", listUsers)
- 传入 middleware 时只对该路由端点生效:GET("/users", listUsers, authMW, rateLimitMW)
- 执行顺序:middleware 按参数顺序依次执行,最后执行 handler
中间件层级体系:
- 全局级:HTTP.UseGlobal(middleware) — 对所有路由生效,等同 Gin engine.Use()
- 组级:Router.Use(middleware) / Router.Group(prefix, middleware) — 对该组下所有路由生效
- 接口级:Router.GET(path, handler, middleware...) — 只对该路由端点生效
type ServiceInstance ¶
type ServiceInstance struct {
ID string
Name string
Address string
Metadata map[string]string
Healthy bool
}
ServiceInstance describes one discovered RPC service instance.
ServiceInstance 描述一个被发现的 RPC 服务实例。
type ServiceRegistry ¶
type ServiceRegistry interface {
Register(ctx context.Context, name, addr string, meta map[string]string) error
Deregister(ctx context.Context, name, addr string) error
Discover(ctx context.Context, name string) ([]ServiceInstance, error)
Close() error
}
ServiceRegistry defines the RPC service discovery registry contract.
ServiceRegistry 定义 RPC 服务发现注册中心契约。
type WebSocketBroadcaster ¶
type WebSocketBroadcaster interface {
// BroadcastString sends a text message to all connections.
// BroadcastString 向所有连接发送文本消息。
BroadcastString(message string) error
// BroadcastBinary sends a binary message to all connections.
// BroadcastBinary 向所有连接发送二进制消息。
BroadcastBinary(data []byte) error
// BroadcastStringExcept sends a text message to all connections except the specified one.
// BroadcastStringExcept 向除指定连接外的所有连接发送文本消息。
BroadcastStringExcept(message string, excludeConn WebSocketConn) error
// BroadcastBinaryExcept sends a binary message to all connections except the specified one.
// BroadcastBinaryExcept 向除指定连接外的所有连接发送二进制消息。
BroadcastBinaryExcept(data []byte, excludeConn WebSocketConn) error
}
WebSocketBroadcaster broadcasts messages to multiple connections.
WebSocketBroadcaster 向多个连接广播消息。
type WebSocketClient ¶
type WebSocketClient interface {
// Conn returns the underlying connection.
// Conn 返回底层连接。
Conn() WebSocketConn
// Close closes the client connection.
// Close 关闭客户端连接。
Close() error
// WriteString sends a text message to the server.
// WriteString 发送文本消息到服务器。
WriteString(message string) error
// WriteBinary sends a binary message to the server.
// WriteBinary 发送二进制消息到服务器。
WriteBinary(data []byte) error
}
WebSocketClient represents a WebSocket client connection.
WebSocketClient 表示 WebSocket 客户端连接。
type WebSocketClientConfig ¶
type WebSocketClientConfig struct {
// Server URL (ws:// or wss://).
// 服务器 URL(ws:// 或 wss://)。
URL string
// Enable compression (permessage-deflate).
// 启用压缩(permessage-deflate)。
EnableCompression bool
// Compression level (1-9, default 6).
// 压缩级别(1-9,默认 6)。
CompressionLevel int
// Max message size in bytes (default 0 = unlimited).
// 最大消息大小(字节),默认 0 表示无限制。
MaxMessageSize int64
// Read buffer size in bytes (default 4096).
// 读缓冲区大小(字节),默认 4096。
ReadBufferSize int
// Write buffer size in bytes (default 4096).
// 写缓冲区大小(字节),默认 4096。
WriteBufferSize int
// Handshake timeout in seconds (default 10).
// 握手超时(秒),默认 10。
HandshakeTimeout int
// Request headers to send during handshake.
// 握手时发送的请求头。
RequestHeader http.Header
}
WebSocketClientConfig holds WebSocket client configuration.
WebSocketClientConfig 保存 WebSocket 客户端配置。
type WebSocketClusterConfig ¶
type WebSocketClusterConfig struct {
// Enable cluster mode.
// 启用集群模式。
Enabled bool
// Node ID for this instance (auto-generated if empty).
// 本实例的节点 ID(为空则自动生成)。
NodeID string
// Redis address for Pub/Sub (e.g., "localhost:6379").
// Redis Pub/Sub 地址(如 "localhost:6379")。
RedisAddr string
// Redis password.
// Redis 密码。
RedisPassword string
// Redis database number.
// Redis 数据库编号。
RedisDB int
// Pub/Sub channel name prefix (default "gorp:ws").
// Pub/Sub 通道名称前缀(默认 "gorp:ws")。
ChannelPrefix string
// Enable global connection count tracking.
// 启用全局连接数统计。
EnableGlobalCount bool
// Connection count key prefix (default "gorp:ws:count").
// 连接数统计键前缀(默认 "gorp:ws:count")。
CountKeyPrefix string
// Heartbeat interval for node health (seconds, default 30).
// 节点健康心跳间隔(秒,默认 30)。
HeartbeatInterval int
}
WebSocketClusterConfig holds WebSocket cluster configuration for multi-node deployment.
WebSocketClusterConfig 保存多节点部署的 WebSocket 集群配置。
type WebSocketClusterServer ¶
type WebSocketClusterServer interface {
WebSocketServer
// BroadcastGlobal broadcasts message to all nodes in the cluster.
// BroadcastGlobal 向集群所有节点广播消息。
BroadcastGlobal(message string) error
// BroadcastGlobalBinary broadcasts binary message to all nodes in the cluster.
// BroadcastGlobalBinary 向集群所有节点广播二进制消息。
BroadcastGlobalBinary(data []byte) error
// BroadcastToRoom broadcasts message to a room across all nodes.
// BroadcastToRoom 向房间广播消息(跨节点)。
BroadcastToRoom(roomID string, message string) error
// GlobalCount returns total connection count across all nodes.
// GlobalCount 返回所有节点的总连接数。
GlobalCount() int
// NodeCount returns connection count for a specific node.
// NodeCount 返回指定节点的连接数。
NodeCount(nodeID string) int
// ListNodes returns all active node IDs.
// ListNodes 返回所有活跃节点 ID。
ListNodes() []string
// GetNodeID returns this node's ID.
// GetNodeID 返回本节点 ID。
GetNodeID() string
}
WebSocketClusterServer extends WebSocketServer with cluster capabilities.
WebSocketClusterServer 扩展 WebSocketServer 的集群能力。
type WebSocketConfig ¶
type WebSocketConfig struct {
// Enable compression (permessage-deflate).
// 启用压缩(permessage-deflate)。
EnableCompression bool
// Compression level (1-9, default 6).
// 压缩级别(1-9,默认 6)。
CompressionLevel int
// Max message size in bytes (default 0 = unlimited).
// 最大消息大小(字节),默认 0 表示无限制。
MaxMessageSize int64
// Read buffer size in bytes (default 4096).
// 读缓冲区大小(字节),默认 4096。
ReadBufferSize int
// Write buffer size in bytes (default 4096).
// 写缓冲区大小(字节),默认 4096。
WriteBufferSize int
// ParallelEnabled enables parallel message processing.
// 启用并行消息处理。
ParallelEnabled bool
// ParallelGolimit is the max goroutines for parallel processing (default runtime.NumCPU).
// 并行处理的最大 goroutine 数,默认 runtime.NumCPU。
ParallelGolimit int
// ReadTimeout sets the maximum duration for reading a message.
// Connections that exceed this timeout will be closed automatically.
// Default 0 means no timeout.
// 读超时,超过此时间的连接将被自动关闭。默认 0 表示无超时。
ReadTimeout time.Duration
// WriteTimeout sets the maximum duration for writing a message.
// Default 0 means no timeout.
// 写超时。默认 0 表示无超时。
WriteTimeout time.Duration
}
WebSocketConfig holds WebSocket server configuration.
WebSocketConfig 保存 WebSocket 服务器配置。
type WebSocketConn ¶
type WebSocketConn interface {
// WriteString sends a text message to the client.
// WriteString 发送文本消息到客户端。
WriteString(message string) error
// WriteBinary sends a binary message to the client.
// WriteBinary 发送二进制消息到客户端。
WriteBinary(data []byte) error
// Close closes the connection with a close code and reason.
// Close 关闭连接,可指定关闭码和原因。
Close(code int, reason string) error
// Context returns the context associated with the connection.
// Context 返回与连接关联的上下文。
Context() context.Context
// SetContext sets the context for the connection.
// SetContext 设置连接的上下文。
SetContext(ctx context.Context)
// RemoteAddr returns the remote address of the connection.
// RemoteAddr 返回连接的远程地址。
RemoteAddr() string
// LocalAddr returns the local address of the connection.
// LocalAddr 返回连接的本地地址。
LocalAddr() string
// RawConn returns the underlying raw connection for advanced usage.
// The returned value is the underlying library's connection type.
// Use with caution - bypassing the abstraction may break framework guarantees.
//
// RawConn 返回底层原生连接供高级使用。
// 返回值是底层库的连接类型。
// 请谨慎使用 - 绕过抽象层可能破坏框架保证。
RawConn() any
}
WebSocketConn represents a WebSocket connection.
WebSocketConn 表示 WebSocket 连接。
type WebSocketHandler ¶
type WebSocketHandler interface {
// OnOpen is called when a new connection is established.
// OnOpen 在新连接建立时调用。
OnOpen(conn WebSocketConn)
// OnClose is called when a connection is closed.
// OnClose 在连接关闭时调用。
OnClose(conn WebSocketConn, err error)
// OnMessage is called when a message is received.
// OnMessage 在收到消息时调用。
OnMessage(conn WebSocketConn, messageType int, data []byte)
}
WebSocketHandler handles WebSocket events.
WebSocketHandler 处理 WebSocket 事件。
type WebSocketServer ¶
type WebSocketServer interface {
// Upgrade upgrades an HTTP connection to WebSocket.
// Upgrade 将 HTTP 连接升级为 WebSocket。
Upgrade(w http.ResponseWriter, r *http.Request, handler WebSocketHandler) (WebSocketConn, error)
// NewBroadcaster creates a new broadcaster for batch message sending.
// NewBroadcaster 创建新的广播器用于批量消息发送。
NewBroadcaster() WebSocketBroadcaster
// Connections returns all active connections.
// Connections 返回所有活跃连接。
Connections() []WebSocketConn
// Count returns the number of active connections.
// Count 返回活跃连接数量。
Count() int
// Shutdown gracefully closes all connections.
// Shutdown 优雅关闭所有连接。
Shutdown(ctx context.Context) error
}
WebSocketServer manages WebSocket connections and provides broadcasting capability.
WebSocketServer 管理 WebSocket 连接并提供广播能力。