* 新增 tools 包:统一工具定义、注册表与 Server 接口,对齐 MCP 规范 * 新增 websocket 包:泛化连接管理、心跳、并发写锁与优雅关闭 * 新增参数读取工具函数,避免类型断言静默失败 * 新增 OSS 路径识别与 JSON 扁平映射还原工具 * 修复租户 SQL 条件插入位置,正确处理 GROUP BY 与 ORDER BY 同时出现的场景
73 lines
2.1 KiB
Go
73 lines
2.1 KiB
Go
package websocket
|
|
|
|
import (
|
|
"context"
|
|
netHttp "net/http"
|
|
"time"
|
|
)
|
|
|
|
// MessageHandler 业务消息处理函数
|
|
type MessageHandler func(ctx context.Context, conn *WsConnection, payload interface{})
|
|
|
|
// WsMessage 通用入站消息
|
|
type WsMessage struct {
|
|
Type string `json:"type"`
|
|
Payload interface{} `json:"payload,omitempty"`
|
|
}
|
|
|
|
// WsPushMsg 通用出站推送消息(业务可自行扩展字段)
|
|
type WsPushMsg struct {
|
|
Type string `json:"type"`
|
|
Message string `json:"message,omitempty"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
// ServerOptions 服务配置
|
|
type ServerOptions struct {
|
|
readTimeout time.Duration
|
|
writeTimeout time.Duration
|
|
heartbeatInterval time.Duration
|
|
workerPoolSize int
|
|
maxConnections int
|
|
connKeyPrefix string
|
|
checkOrigin func(r *netHttp.Request) bool
|
|
}
|
|
|
|
// ServerOption 配置函数
|
|
type ServerOption func(*ServerOptions)
|
|
|
|
func WithReadTimeout(d time.Duration) ServerOption {
|
|
return func(o *ServerOptions) { o.readTimeout = d }
|
|
}
|
|
func WithWriteTimeout(d time.Duration) ServerOption {
|
|
return func(o *ServerOptions) { o.writeTimeout = d }
|
|
}
|
|
func WithHeartbeatInterval(d time.Duration) ServerOption {
|
|
return func(o *ServerOptions) { o.heartbeatInterval = d }
|
|
}
|
|
func WithWorkerPoolSize(n int) ServerOption {
|
|
return func(o *ServerOptions) { o.workerPoolSize = n }
|
|
}
|
|
func WithMaxConnections(n int) ServerOption {
|
|
return func(o *ServerOptions) { o.maxConnections = n }
|
|
}
|
|
func WithConnKeyPrefix(p string) ServerOption {
|
|
return func(o *ServerOptions) { o.connKeyPrefix = p }
|
|
}
|
|
func WithCheckOrigin(fn func(r *netHttp.Request) bool) ServerOption {
|
|
return func(o *ServerOptions) { o.checkOrigin = fn }
|
|
}
|
|
|
|
func defaultOptions() ServerOptions {
|
|
return ServerOptions{
|
|
readTimeout: DefaultReadTimeout,
|
|
writeTimeout: DefaultWriteTimeout,
|
|
heartbeatInterval: DefaultHeartbeatInterval,
|
|
workerPoolSize: DefaultWorkerPoolSize,
|
|
maxConnections: DefaultMaxConnections,
|
|
connKeyPrefix: DefaultConnKeyPrefix,
|
|
checkOrigin: func(r *netHttp.Request) bool { return true },
|
|
}
|
|
}
|