node

package
v1.1.7 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GatewayRateLimiterFilterName = "GatewayRateLimiterFilter" // 网关限流过滤器
	ParameterFilterName          = "ParameterFilter"          // 参数解析过滤器
	SessionFilterName            = "SessionFilter"            // 会话验证过滤器
	UserRateLimiterFilterName    = "UserRateLimiterFilter"    // 用户限流过滤器
	RoleFilterName               = "RoleFilter"               // 角色权限过滤器
	PostHandleFilterName         = "PostHandleFilter"         // 后置处理过滤器
	RenderHandleFilterName       = "RenderHandleFilter"       // 响应渲染过滤器
)

过滤器名称常量定义 用于标识不同类型的过滤器,方便配置和管理

View Source
const (
	UTF8 = "UTF-8"

	ANDROID = "android"
	IOS     = "ios"
	WEB     = "web"

	TEXT_PLAIN       = "text/plain; charset=utf-8"
	APPLICATION_JSON = "application/json; charset=utf-8"
	NO_BODY          = "no_body"

	GET     = "GET"
	POST    = "POST"
	PUT     = "PUT"
	PATCH   = "PATCH"
	DELETE  = "DELETE"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"

	Authorization = "Authorization"
	SharedKey     = "SharedKey"
	Cipher        = "Cipher"

	SharedInfo = "freego-ecdh-aes-gcm"
)
View Source
const (
	DefaultWsRoute      = "/ws"       // 默认WebSocket路由路径
	DefaultWsMaxBodyLen = 1024 * 1024 // 默认单条消息体最大 1MB,可通过 WsServer.SetMaxBodyLen 覆盖
)

WebSocket服务器实现

错误类型约定:

  • 协议错误(客户端请求不合法、鉴权失败等):使用 ex.Throw{Code, Msg[, Err]},便于上层按 HTTP 状态码处理或回写。
  • 配置/内部错误(校验配置、连接池、调用方参数等):使用 utils.Error,仅作日志或返回给调用方,无状态码需求。

WebSocket专用常量

Variables

View Source
var (
	MAX_BODY_LEN  = 200000 // 最大参数值长度
	MAX_TOKEN_LEN = 2048   // 最大Token值长度
	MAX_CODE_LEN  = 1024   // 最大Code值长度
)

Functions

func AppendBodyMessage added in v1.1.0

func AppendBodyMessage(path, data, nonce string, time, plan, usr int64) []byte

func CheckPublicKey added in v1.1.0

func CheckPublicKey(c cache.Cache, requestObject *PublicKey, cipher crypto.Cipher) error

func ErrorMsgToLang added in v1.0.129

func ErrorMsgToLang(ctx *Context, msg string, args ...string) string

func HKDFKey added in v1.1.4

func HKDFKey(shared []byte, nonce string) ([]byte, error)

func NewGracefulListener

func NewGracefulListener(address string, maxWaitTime time.Duration) (net.Listener, error)

NewGracefulListener 创建一个新的优雅关闭监听器 返回 (监听器, 错误),避免直接panic,让调用者处理初始化失败

func PutJsonBody added in v1.1.0

func PutJsonBody(body *JsonBody)

PutJsonBody 将JsonBody对象放回对象池 注意:放回前需要重置对象字段,避免数据污染

func PutJsonResp added in v1.1.0

func PutJsonResp(resp *JsonResp)

PutJsonResp 将JsonResp对象放回对象池 注意:放回前需要重置对象字段,避免数据污染

func PutMessageHandler added in v1.1.0

func PutMessageHandler(mh *MessageHandler)

PutMessageHandler 将MessageHandler对象放回池中,并重置其字段

func SignBodyMessage added in v1.1.0

func SignBodyMessage(path, data, nonce string, time, plan, usr int64, key []byte) []byte

Types

type CacheAware added in v1.0.5

type CacheAware func(ds ...string) (cache.Cache, error)

type ConfigValidator added in v1.1.0

type ConfigValidator struct{}

ConfigValidator 配置验证器(统一配置检查)

type Configs added in v1.0.113

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

Configs 结构体 - 88字节 (4个字段,8字节对齐,无填充) 排列优化:大字段优先,string放在最后利用16字节对齐

type ConnectionContext added in v1.1.0

type ConnectionContext struct {
	Subject      *jwt.Subject
	JsonBody     *JsonBody
	WsConn       net.Conn // WebSocket 连接(gobwas/ws 使用 net.Conn)
	DevConn      *DevConn
	Server       *WsServer
	RouterConfig *RouterConfig // 路由配置
	Path         string        // WebSocket连接的路径
	RawToken     []byte        // 原始JWT token字节,用于签名验证
	// contains filtered or unexported fields
}

ConnectionContext 每个WebSocket连接的上下文,包含连接相关的所有信息。

设计要点:JsonBody 由 processMessage 从对象池获取并注入,业务 Handle 只读使用,不得在返回后继续持有。

func (*ConnectionContext) GetRawTokenBytes added in v1.1.0

func (cc *ConnectionContext) GetRawTokenBytes() []byte

GetRawTokenBytes 获取原始JWT token字节

func (*ConnectionContext) GetTokenSecret added in v1.1.0

func (cc *ConnectionContext) GetTokenSecret() []byte

GetTokenSecret 获取WebSocket连接的 token 派生密钥(每次调用重新派生,不缓存)。 为保证安全需在用毕后 DIC.ClearData(secret);为此接受每次 HMAC 派生的性能损耗。

func (*ConnectionContext) GetUserID added in v1.1.0

func (cc *ConnectionContext) GetUserID() int64

GetUserID 获取用户ID int64类型

func (*ConnectionContext) GetUserIDString added in v1.1.0

func (cc *ConnectionContext) GetUserIDString() string

GetUserIDString 获取用户ID string类型

type ConnectionManager added in v1.1.0

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

ConnectionManager 连接管理器:线程安全的连接管理,支持广播、按 subject 推送、过期清理。

设计要点: - conns:二级 map subject -> deviceKey -> *DevConn,deviceKey 由 mode 决定(SubjectUnique 时为 sub,SubjectDeviceUnique 时为 sub_dev)。 - totalConn:原子计数,用于限流、Count()、以及 CleanupExpired/sendToSubjectByJsonResp 的 slice 预分配容量,避免在 RLock 内做重逻辑。 - 所有“收集 conn 再关闭/发送”的路径均在 RLock 内只收集指针,在锁外执行 I/O,避免持锁时间过长。

func NewConnectionManager added in v1.1.0

func NewConnectionManager(maxConn int, mode ConnectionUniquenessMode, broadcastKey string) *ConnectionManager

NewConnectionManager 创建连接管理器

func (*ConnectionManager) Add added in v1.1.0

func (cm *ConnectionManager) Add(conn *DevConn) error

Add 添加连接 Add 将连接加入管理器。根据连接唯一性模式决定策略: - SubjectUnique: 替换同 subject 的所有连接,只保留一个。 - SubjectDeviceUnique: 替换同 subject+device 的连接,允许多设备同时在线。 设备键格式:subject_device (如: user123_web, user123_app)

设计要点:若存在旧连接,先从 map 移除并减 totalConn,再在 goroutine 中 closeConn,避免锁内 I/O 阻塞。

func (*ConnectionManager) AddTestConnection added in v1.1.0

func (cm *ConnectionManager) AddTestConnection(subject, deviceKey string, conn *DevConn)

AddTestConnection 添加测试连接(仅用于单元测试)

func (*ConnectionManager) Broadcast added in v1.1.0

func (cm *ConnectionManager) Broadcast(data []byte)

Broadcast 广播消息到所有连接。 连接活性由 LastSeen 与 CleanupExpired 维护;Send 内部会检查 closed 并安全返回错误。

func (*ConnectionManager) CleanupAll added in v1.1.0

func (cm *ConnectionManager) CleanupAll()

CleanupAll 关闭所有连接。先 RLock 内收集全部 conn 指针并预分配 slice,锁外再统一 closeConn,由各连接循环执行 RemoveByConn + ws.Close()。

func (*ConnectionManager) CleanupExpired added in v1.1.0

func (cm *ConnectionManager) CleanupExpired(timeoutSeconds int64) int

CleanupExpired 清理空闲超过 timeoutSeconds 的连接。

设计要点: - 在 RLock 内仅收集过期 conn 指针(LastSeen 为原子读无锁),RUnlock 后再 closeConn,避免持锁做 I/O。 - toClose 按 totalConn 预分配容量,减少 append 扩容与 GC。 - 超时判断依赖 DevConn.Last(每次收包/心跳 UpdateLast),由 HeartbeatService 按 idleTimeout 周期性调用。

func (*ConnectionManager) Count added in v1.1.0

func (cm *ConnectionManager) Count() int

Count 获取当前连接数

func (*ConnectionManager) Get added in v1.1.0

func (cm *ConnectionManager) Get(subject, deviceKey string) *DevConn

Get 获取指定连接

func (*ConnectionManager) GetAllSubjectDevices added in v1.1.3

func (cm *ConnectionManager) GetAllSubjectDevices() map[string][]string

GetAllSubjectDevices 获取所有用户连接subject

func (*ConnectionManager) GetSubjectDevices added in v1.1.3

func (cm *ConnectionManager) GetSubjectDevices(subject string) map[string][]string

GetSubjectDevices

func (*ConnectionManager) HealthCheck added in v1.1.0

func (cm *ConnectionManager) HealthCheck() map[string]int

HealthCheck 健康检查:返回每个 subject 的连接数。 活性由 LastSeen 与 CleanupExpired 维护。

func (*ConnectionManager) Remove added in v1.1.0

func (cm *ConnectionManager) Remove(subject, deviceKey string) *DevConn

Remove 移除连接(不关闭,仅从管理器移除)

func (*ConnectionManager) RemoveByConn added in v1.1.6

func (cm *ConnectionManager) RemoveByConn(conn *DevConn) bool

RemoveByConn 按连接指针从管理器中移除该连接。 设计要点:必须用指针精确匹配,避免“新连接已替换旧连接”时误把新连接从 map 删掉;关闭由 closeConnFromLoop 等调用方负责。 返回是否成功移除(若连接已被替换则未找到,返回 false)。

func (*ConnectionManager) RemoveWithCallback added in v1.1.0

func (cm *ConnectionManager) RemoveWithCallback(subject, deviceKey string, callback func()) *DevConn

RemoveWithCallback 移除连接并执行回调(用于指标记录)

func (*ConnectionManager) SendToSubject added in v1.1.0

func (cm *ConnectionManager) SendToSubject(subject, router string, data interface{}) error

SendToSubject 发送消息到指定主题的所有连接

type ConnectionUniquenessMode added in v1.1.0

type ConnectionUniquenessMode int

ConnectionUniquenessMode 连接唯一性模式 用于控制WebSocket连接的唯一性策略

const (
	// SubjectUnique 仅Subject唯一,一个用户只能有一个连接
	// 适用于单设备应用场景,如移动端App
	SubjectUnique ConnectionUniquenessMode = iota

	// SubjectDeviceUnique Subject+Device唯一,一个用户可以在多个设备上连接
	// 适用于多设备场景,如Web、App、PC同时在线
	SubjectDeviceUnique
)

type Context

type Context struct {
	// 16字节string字段组 (2个字段,32字节)
	Method string // 16字节 (8+8) - string字段
	Path   string // 16字节 (8+8) - string字段

	System     *System              // 8字节 - 指针
	RequestCtx *fasthttp.RequestCtx // 8字节 - 指针
	Subject    *jwt.Subject         // 8字节 - 指针
	JsonBody   *JsonBody            // 8字节 - 指针
	Response   *Response            // 8字节 - 指针

	RouterConfig *RouterConfig // 8字节 - 指针

	// 8字节函数指针字段组 (5个字段,40字节)
	RedisCacheAware func(ds ...string) (cache.Cache, error) // 8字节 - 函数指针
	LocalCacheAware func(ds ...string) (cache.Cache, error) // 8字节 - 函数指针

	// 8字节其他字段组 (2个字段)
	Cipher  map[int64]crypto.Cipher // 8字节 - slice
	Storage map[string]interface{}  // 8字节 - map
	// contains filtered or unexported fields
}

Context 结构体 - 184字节 (19个字段,8字节对齐,0字节填充) 排列优化:按字段大小和类型分组,16字节string字段在前,8字节指针/函数/map字段居中,bool字段在后

func (*Context) AddStorage

func (self *Context) AddStorage(k string, v interface{})

func (*Context) Authenticated

func (self *Context) Authenticated() bool

func (*Context) Bytes added in v1.1.0

func (self *Context) Bytes(data []byte) error

func (*Context) CheckECDSASign added in v1.1.0

func (self *Context) CheckECDSASign(cipher crypto.Cipher, msg, sign []byte) (crypto.Cipher, error)

func (*Context) ClientDevice added in v1.0.104

func (self *Context) ClientDevice() string

func (*Context) ClientLanguage added in v1.0.107

func (self *Context) ClientLanguage() string

func (*Context) CreatePublicKey added in v1.1.0

func (self *Context) CreatePublicKey() (*PublicKey, error)

func (*Context) DelStorage added in v1.0.3

func (self *Context) DelStorage(k string)

func (*Context) GetCacheObject added in v1.1.0

func (self *Context) GetCacheObject() (cache.Cache, error)

func (*Context) GetHeader added in v1.0.134

func (self *Context) GetHeader(key string) string

func (*Context) GetHmac256Sign

func (self *Context) GetHmac256Sign(d, n string, t, p, u int64, key []byte) []byte

func (*Context) GetJwtConfig

func (self *Context) GetJwtConfig() jwt.JwtConfig

func (*Context) GetPostBody added in v1.0.134

func (self *Context) GetPostBody() string

func (*Context) GetRawTokenBytes added in v1.1.0

func (self *Context) GetRawTokenBytes() []byte

func (*Context) GetStorage

func (self *Context) GetStorage(k string) interface{}

func (*Context) GetTokenSecret

func (self *Context) GetTokenSecret() []byte

func (*Context) Handle

func (self *Context) Handle() error

func (*Context) Json added in v1.0.120

func (self *Context) Json(data interface{}) error

func (*Context) NoBody added in v1.0.170

func (self *Context) NoBody() error

func (*Context) Parser

func (self *Context) Parser(dst interface{}) error

func (*Context) RemoteIP added in v1.0.104

func (self *Context) RemoteIP() string

RemoteIP 安全获取真实客户端IP(防伪造、过滤内网IP)

func (*Context) Text added in v1.0.120

func (self *Context) Text(data string) error

type DevConn added in v1.0.146

type DevConn struct {
	Sub  string
	Dev  string
	Last int64    // 最后活跃时间戳,原子读写,供 CleanupExpired 无锁判断
	Conn net.Conn // WebSocket 连接(gobwas/ws)
	// contains filtered or unexported fields
}

DevConn 设备连接实体:存储单连接的核心信息。

设计要点: - Last:使用原子读写(UpdateLast 写、LastSeen 读),使 CleanupExpired 遍历时无需对每条连接加 sendMu,降低高连接数下的锁竞争。 - sendMu:仅保护 Conn 的写与 closed 的可见性,Send/关闭路径使用;Last 不再依赖 sendMu。 - closeOnce:保证 ws.Close() 只执行一次,避免重复关闭导致 panic。

func (*DevConn) LastSeen added in v1.1.6

func (dc *DevConn) LastSeen() int64

LastSeen 返回最近一次活跃时间。原子读、无锁,供 CleanupExpired 在 RLock 内批量调用而不产生 sendMu 竞争。

func (*DevConn) Send added in v1.1.0

func (dc *DevConn) Send(data []byte) error

Send 向连接写入一条文本消息。所有对 Conn 与 closed 的访问均在 sendMu 内,避免与 closeConnFromLoop 竞态导致空指针或重复写。

func (*DevConn) UpdateLast added in v1.1.6

func (dc *DevConn) UpdateLast()

UpdateLast 更新连接最后活跃时间。原子写,无锁,便于消息循环中高频调用且不影响 CleanupExpired 遍历。

type ErrorHandle added in v1.0.121

type ErrorHandle func(ctx *Context, throw ex.Throw) error

type ErrorHandler added in v1.1.0

type ErrorHandler struct {
}

ErrorHandler WebSocket错误处理器(统一错误处理)

type Filter

type Filter interface {
	DoFilter(chain Filter, ctx *Context, args ...interface{}) error
}

type FilterObject

type FilterObject struct {
	Name         string   // 16字节 (8+8) - string字段
	Filter       Filter   // 16字节 (8+8) - interface{}字段
	MatchPattern []string // 24字节 (8+8+8) - slice字段
	Order        int      // 8字节 - int字段放在最后
}

FilterObject 结构体 - 64字节 (4个字段,8字节对齐,优化排列减少填充) 排列优化:大字段优先,相同大小字段分组

type GatewayRateLimiterFilter

type GatewayRateLimiterFilter struct{} // 网关级限流过滤器

过滤器结构体定义 实现Filter接口的DoFilter方法,按照职责分离的原则处理不同的过滤逻辑

func (*GatewayRateLimiterFilter) DoFilter

func (self *GatewayRateLimiterFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行网关级和方法级限流检查 1. 网关级限流:全局请求频率控制 2. 方法级限流:按API路径进行精细化频率控制 如果请求超出限制,返回429 Too Many Requests错误

type GracefulListener

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

GracefulListener 支持优雅关闭的TCP监听器,关闭时会等待现有连接处理完毕

func (*GracefulListener) Accept

func (ln *GracefulListener) Accept() (net.Conn, error)

func (*GracefulListener) Addr

func (ln *GracefulListener) Addr() net.Addr

Addr 返回监听器的地址信息

func (*GracefulListener) Close

func (ln *GracefulListener) Close() error

Close 关闭监听器并等待所有活跃连接处理完毕(优雅关闭) 1. 先关闭底层监听器,停止接受新连接 2. 等待现有连接关闭,超时则返回错误

func (*GracefulListener) CloseWithTimeout added in v1.1.0

func (ln *GracefulListener) CloseWithTimeout(timeout time.Duration) error

CloseWithTimeout 带超时的优雅关闭

type Handle added in v1.0.146

type Handle func(ctx context.Context, connCtx *ConnectionContext, body []byte) (interface{}, error)

核心类型定义 Handle 业务处理函数,返回 nil 则不回复。 对象池约束:返回的 *JsonResp 等由框架在 replyData 内统一 Put 回池;handler 不得在返回后继续持有或异步使用 connCtx.JsonBody/GetJsonResp 等池对象,应同步处理完毕。

type HeartbeatService added in v1.1.0

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

HeartbeatService 心跳服务:维护连接活性,清理过期连接

func NewHeartbeatService added in v1.1.0

func NewHeartbeatService(interval, timeout time.Duration, manager *ConnectionManager) *HeartbeatService

func (*HeartbeatService) Start added in v1.1.0

func (hs *HeartbeatService) Start()

func (*HeartbeatService) Stop added in v1.1.0

func (hs *HeartbeatService) Stop()

type HookNode

type HookNode struct {
	Context *Context // 8字节 - 指针字段
	// contains filtered or unexported fields
}

HookNode 结构体 - 32字节 (2个字段,8字节对齐,无填充) 排列优化:指针字段在前,slice字段在后

type HttpLog

type HttpLog struct {
	Method   string // 请求方法 - 16字节 (8+8)
	LogNo    string // 日志唯一标记 - 16字节 (8+8)
	CreateAt int64  // 日志创建时间 - 8字节
	UpdateAt int64  // 日志完成时间 - 8字节
	CostMill int64  // 业务耗时,毫秒 - 8字节
}

HttpLog 结构体 - 64字节 (5个字段,8字节对齐,无填充) 排列优化:string字段在前,int64字段连续排列

type HttpNode

type HttpNode struct {
	HookNode
	// contains filtered or unexported fields
}

func (*HttpNode) AddCipher added in v1.0.72

func (self *HttpNode) AddCipher(key int64, cipher crypto.Cipher) error

func (*HttpNode) AddErrorHandle added in v1.0.121

func (self *HttpNode) AddErrorHandle(errorHandle func(ctx *Context, throw ex.Throw) error) error

func (*HttpNode) AddFilter

func (self *HttpNode) AddFilter(object *FilterObject)

func (*HttpNode) AddJwtConfig

func (self *HttpNode) AddJwtConfig(config jwt.JwtConfig) error

func (*HttpNode) AddLanguage added in v1.0.107

func (self *HttpNode) AddLanguage(langDs, filePath string) error

func (*HttpNode) AddLanguageByJson added in v1.0.128

func (self *HttpNode) AddLanguageByJson(langDs string, bs []byte) error

func (*HttpNode) AddLocalCache added in v1.1.0

func (self *HttpNode) AddLocalCache(cacheAware CacheAware)

AddLocalCache 增加本地缓存实例

func (*HttpNode) AddRedisCache added in v1.1.0

func (self *HttpNode) AddRedisCache(cacheAware CacheAware)

AddRedisCache 增加redis缓存实例

func (*HttpNode) AddRoleRealm added in v1.0.115

func (self *HttpNode) AddRoleRealm(roleRealm func(ctx *Context, onlyRole bool) (*Permission, error)) error

func (*HttpNode) Bytes added in v1.1.0

func (self *HttpNode) Bytes(ctx *Context, data []byte) error

func (*HttpNode) ClearFilterChain

func (self *HttpNode) ClearFilterChain()

func (*HttpNode) DELETE

func (self *HttpNode) DELETE(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) Empty added in v1.0.170

func (self *HttpNode) Empty(ctx *Context) error

func (*HttpNode) EnableECC added in v1.0.72

func (self *HttpNode) EnableECC(enable bool)

EnableECC default: true

func (*HttpNode) GET

func (self *HttpNode) GET(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) HEAD

func (self *HttpNode) HEAD(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) Json

func (self *HttpNode) Json(ctx *Context, data interface{}) error

func (*HttpNode) OPTIONS

func (self *HttpNode) OPTIONS(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) PATCH

func (self *HttpNode) PATCH(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) POST

func (self *HttpNode) POST(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) PUT

func (self *HttpNode) PUT(path string, handle func(ctx *Context) error, routerConfig *RouterConfig)

func (*HttpNode) SetDefaultMethodRateLimiter added in v1.1.0

func (self *HttpNode) SetDefaultMethodRateLimiter(option rate.Option)

func (*HttpNode) SetDynamicSecretKey added in v1.1.3

func (self *HttpNode) SetDynamicSecretKey(key string)

SetDynamicSecretKey 增加本地secret定义,最少24个字符长度

func (*HttpNode) SetGatewayRateLimiter added in v1.1.0

func (self *HttpNode) SetGatewayRateLimiter(option rate.Option)

SetGatewayRateLimiter 设置网关级限流器配置 用于控制整个服务的全局请求频率,防止服务过载 option: 限流器配置,包含速率和桶容量等参数

func (*HttpNode) SetLengthCheck added in v1.1.0

func (self *HttpNode) SetLengthCheck(bodyLen, tokenLen, codeLen int)

func (*HttpNode) SetMethodRateLimiterByPath added in v1.1.0

func (self *HttpNode) SetMethodRateLimiterByPath(path string, option rate.Option)

SetMethodRateLimiterByPath 为特定路径设置方法级限流器

func (*HttpNode) SetSystem added in v1.0.115

func (self *HttpNode) SetSystem(name, version string)

func (*HttpNode) SetUserRateLimiter added in v1.1.0

func (self *HttpNode) SetUserRateLimiter(option rate.Option)

SetUserRateLimiter 设置用户级限流器配置 用于控制每个用户的请求频率,防止恶意用户刷接口 option: 限流器配置,通常设置较低的速率限制

func (*HttpNode) StartServer

func (self *HttpNode) StartServer(addr string)

func (*HttpNode) StartServerByTimeout added in v1.0.172

func (self *HttpNode) StartServerByTimeout(addr string, timeout int)

func (*HttpNode) Text

func (self *HttpNode) Text(ctx *Context, data string) error

type JsonBody

type JsonBody struct {
	// 16字节字段组 (3个string字段,48字节)
	Data   string `json:"d"` // 16字节 (8+8) - string字段
	Nonce  string `json:"n"` // 16字节 (8+8) - string字段
	Sign   string `json:"s"` // 16字节 (8+8) - string字段
	Valid  string `json:"e"` // 16字节 (8+8) - string字段
	Router string `json:"r"` // 16字节 (8+8) - string字段

	// 8字节字段组 (2个int64字段,16字节)
	Time int64 `json:"t"` // 8字节 - int64字段
	Plan int64 `json:"p"` // 8字节 - 0.默认(登录状态) 1.AES(登录状态) 2.RSA/ECC模式(匿名状态)
	User int64 `json:"u"` // 8字节 - 客户端ID
}

JsonBody 结构体 - 64字节 (5个字段,8字节对齐,无填充) 排列优化:string字段组在前(48字节),int64字段组在后(16字节)

func GetJsonBody added in v1.1.0

func GetJsonBody() *JsonBody

GetJsonBody 从对象池获取JsonBody对象

func (JsonBody) MarshalEasyJSON added in v1.1.0

func (v JsonBody) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (JsonBody) MarshalJSON added in v1.1.0

func (v JsonBody) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*JsonBody) ParseData added in v1.0.22

func (self *JsonBody) ParseData(dst interface{}) error

func (*JsonBody) RawData added in v1.0.22

func (self *JsonBody) RawData() []byte

func (*JsonBody) UnmarshalEasyJSON added in v1.1.0

func (v *JsonBody) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*JsonBody) UnmarshalJSON added in v1.1.0

func (v *JsonBody) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type JsonResp

type JsonResp struct {
	// 16字节字段组 (4个string字段,64字节)
	Message string `json:"m"` // 16字节 (8+8) - string字段
	Data    string `json:"d"` // 16字节 (8+8) - string字段
	Nonce   string `json:"n"` // 16字节 (8+8) - string字段
	Sign    string `json:"s"` // 16字节 (8+8) - string字段
	Valid   string `json:"e"` // 16字节 (8+8) - string字段
	Router  string `json:"r"` // 16字节 (8+8) - 路由字段,用于消息订阅

	// 8字节字段组 (3个字段:1个int+2个int64,24字节)
	Code int   `json:"c"` // 8字节 - int字段
	Time int64 `json:"t"` // 8字节 - int64字段
	Plan int64 `json:"p"` // 8字节 - int64字段
}

JsonResp 结构体 - 96字节 (7个字段,8字节对齐,无填充) 排列优化:string字段组在前(64字节),int和int64字段组在后(32字节)

func GetJsonResp added in v1.1.0

func GetJsonResp() *JsonResp

GetJsonResp 从对象池获取JsonResp对象

func (JsonResp) MarshalEasyJSON added in v1.1.0

func (v JsonResp) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (JsonResp) MarshalJSON added in v1.1.0

func (v JsonResp) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*JsonResp) UnmarshalEasyJSON added in v1.1.0

func (v *JsonResp) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*JsonResp) UnmarshalJSON added in v1.1.0

func (v *JsonResp) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type MessageHandler added in v1.1.0

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

MessageHandler 消息处理器:统一处理消息校验、解码、路由

func GetMessageHandler added in v1.1.0

func GetMessageHandler(cipher map[int64]crypto.Cipher, handle Handle) *MessageHandler

GetMessageHandler 从池中获取一个MessageHandler对象

func NewMessageHandler added in v1.1.0

func NewMessageHandler(cipher map[int64]crypto.Cipher, handle Handle) *MessageHandler

func (*MessageHandler) CheckECDSASign added in v1.1.0

func (self *MessageHandler) CheckECDSASign(usr int64, msg, sign []byte) (crypto.Cipher, error)

func (*MessageHandler) Process added in v1.1.0

func (mh *MessageHandler) Process(connCtx *ConnectionContext, body []byte) (crypto.Cipher, interface{}, error)

type ParameterFilter

type ParameterFilter struct{} // 参数解析过滤器

func (*ParameterFilter) DoFilter

func (self *ParameterFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行参数解析和验证 从HTTP请求中解析参数并存储到上下文,供后续处理使用 如果参数解析失败,返回相应的错误信息

type Permission

type Permission struct {
	MatchAll  bool    // true.满足所有权限角色才放行 - 1字节
	NeedLogin bool    // true.需要登录状态 - 1字节
	HasRole   []int64 // 拥有角色ID列表 - 24字节 (8+8+8)
	NeedRole  []int64 // 所需角色ID列表 - 24字节 (8+8+8)
}

Permission 结构体 - 48字节 (4个字段,8字节对齐,0字节填充) 排列优化:bool字段在前,slice字段连续排列,利用8字节对齐

type PostHandle

type PostHandle func(*Context) error

type PostHandleFilter

type PostHandleFilter struct{} // 后置处理过滤器

func (*PostHandleFilter) DoFilter

func (self *PostHandleFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行后置处理逻辑 在业务处理完成后执行清理、日志记录等操作 确保响应的一致性和完整性

type PrivateKey added in v1.1.0

type PrivateKey struct {
	Key string `json:"key"` // 私钥Base64编码格式
	Noc string `json:"noc"` // 随机数
}

func (PrivateKey) MarshalEasyJSON added in v1.1.0

func (v PrivateKey) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (PrivateKey) MarshalJSON added in v1.1.0

func (v PrivateKey) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*PrivateKey) UnmarshalEasyJSON added in v1.1.0

func (v *PrivateKey) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*PrivateKey) UnmarshalJSON added in v1.1.0

func (v *PrivateKey) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type PublicKey added in v1.1.0

type PublicKey struct {
	Key string `json:"key"` // 服务端临时公钥
	Tag string `json:"tag"` // 客户端临时公钥
	Noc string `json:"noc"` // 随机数
	Sig string `json:"sig"` // 数据签名
	Exp int64  `json:"exp"` // 有效时间,单位秒
	Usr int64  `json:"usr"` // 客户端ID
}

func CreatePublicKey added in v1.1.0

func CreatePublicKey(key, tag string, usr int64, cipher crypto.Cipher) (*PublicKey, error)

func (PublicKey) MarshalEasyJSON added in v1.1.0

func (v PublicKey) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (PublicKey) MarshalJSON added in v1.1.0

func (v PublicKey) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*PublicKey) UnmarshalEasyJSON added in v1.1.0

func (v *PublicKey) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*PublicKey) UnmarshalJSON added in v1.1.0

func (v *PublicKey) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type RenderHandleFilter

type RenderHandleFilter struct{} // 响应渲染过滤器

func (*RenderHandleFilter) DoFilter

func (self *RenderHandleFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行最终的响应渲染和输出 将处理结果序列化并输出到HTTP响应中 这是过滤器链的最后一个环节,确保响应正确返回给客户端

type Response

type Response struct {
	Encoding          string       // 16字节 (8+8) - string字段
	ContentType       string       // 16字节 (8+8) - string字段
	ContentEntity     interface{}  // 16字节 (8+8) - interface{}字段
	StatusCode        int          // 8字节 - int字段
	ContentEntityByte bytes.Buffer // 24字节 - bytes.Buffer (包含内部字段)
}

Response 结构体 - 80字节 (5个字段,8字节对齐,0字节填充) 排列优化:string和interface{}字段在前,int字段和复杂类型字段在后

type RoleFilter

type RoleFilter struct{} // 角色权限过滤器

func (*RoleFilter) DoFilter

func (self *RoleFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行基于角色的访问控制(RBAC) 根据用户角色和API要求的权限进行访问控制验证 支持"全部匹配"和"任意匹配"两种权限验证模式

type RouteInfo added in v1.1.0

type RouteInfo struct {
	Handle       Handle        // 业务处理器
	RouterConfig *RouterConfig // 路由配置
}

RouteInfo WebSocket路由信息结构体

type RouterConfig

type RouterConfig struct {
	Guest       bool // 游客模式,原始请求 false.否 true.是 - 1字节
	UseRSA      bool // 非登录状态使用RSA模式请求 false.否 true.是 - 1字节
	AesRequest  bool // 请求是否必须AES加密 false.否 true.是 - 1字节
	AesResponse bool // 响应是否必须AES加密 false.否 true.是 - 1字节
}

RouterConfig 结构体 - 4字节 (4个bool字段,1字节对齐) 排列优化:bool字段自然排列,无填充问题

type SessionFilter

type SessionFilter struct{} // 会话验证过滤器

func (*SessionFilter) DoFilter

func (self *SessionFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行会话验证和身份认证 检查用户是否已登录,解析JWT令牌并验证其有效性 为已认证用户设置Subject信息,供后续过滤器使用

type System added in v1.0.116

type System struct {
	Name    string // 系统名 - 16字节 (8+8)
	Version string // 系统版本 - 16字节 (8+8)

	AcceptTimeout int64 // 超时主动断开客户端连接,秒 - 8字节
	// contains filtered or unexported fields
}

System 结构体 - 40字节 (4个字段,8字节对齐,0字节填充) 排列优化:string字段在前,bool字段居中,int64字段在后,利用8字节对齐

type UserRateLimiterFilter

type UserRateLimiterFilter struct{} // 用户级限流过滤器

func (*UserRateLimiterFilter) DoFilter

func (self *UserRateLimiterFilter) DoFilter(chain Filter, ctx *Context, args ...interface{}) error

DoFilter 执行用户级限流检查 针对已认证用户进行个性化频率限制,防止恶意刷接口行为 每个用户的请求频率单独计算和限制

type WebSocketMetrics added in v1.1.0

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

WebSocketMetrics WebSocket监控指标

type WsServer added in v1.0.146

type WsServer struct {

	// ECC和缓存配置(用于Plan 2)
	// 8字节函数指针字段组 (5个字段,40字节)
	Cipher          map[int64]crypto.Cipher                 // 8字节 - RSA/ECDSA加密解密对象列表
	RedisCacheAware func(ds ...string) (cache.Cache, error) // 8字节 - 函数指针
	LocalCacheAware func(ds ...string) (cache.Cache, error) // 8字节 - 函数指针
	// contains filtered or unexported fields
}

WsServer WebSocket服务器核心结构体

func NewWsServer added in v1.1.0

func NewWsServer(connUniquenessMode ConnectionUniquenessMode) *WsServer

NewWsServer 创建WebSocket服务器 connUniquenessMode: 连接唯一性模式

  • SubjectUnique: 一个用户只能有一个连接(适用于单设备应用)
  • SubjectDeviceUnique: 一个用户可以在多个设备上连接(适用于多设备场景)

func (*WsServer) AddCipher added in v1.1.0

func (self *WsServer) AddCipher(usr int64, cipher crypto.Cipher) error

AddCipher 注册 ECDSA/RSA 加解密对象,用于 Plan 1 等场景的请求验签与响应签名。 应在 StartWebsocket 之前完成所有注册。不支持运行期动态添加(MessageHandler 无锁读 Cipher,动态添加有并发风险);若以后需要运行期扩展再考虑加锁或 copy-on-write 等方案。

func (*WsServer) AddJwtConfig added in v1.0.146

func (self *WsServer) AddJwtConfig(config jwt.JwtConfig) error

AddJwtConfig 添加JWT配置

func (*WsServer) AddLocalCache added in v1.1.0

func (self *WsServer) AddLocalCache(cacheAware CacheAware)

AddLocalCache 增加本地缓存实例

func (*WsServer) AddRedisCache added in v1.1.0

func (self *WsServer) AddRedisCache(cacheAware CacheAware)

AddRedisCache 增加redis缓存实例

func (*WsServer) AddRouter added in v1.0.146

func (s *WsServer) AddRouter(path string, handle Handle, routerConfig *RouterConfig) error

AddRouter 注册路由:path -> Handle。应在 StartWebsocket 之前完成所有注册。 不支持在服务启动后动态添加:消息循环中会无锁读 s.routes,动态添加会产生并发读写风险。

func (*WsServer) GetCacheObject added in v1.1.0

func (self *WsServer) GetCacheObject() (cache.Cache, error)

GetCacheObject 获取缓存对象

func (*WsServer) GetConnManager added in v1.1.0

func (s *WsServer) GetConnManager() *ConnectionManager

GetConnManager 获取连接管理器(用于测试)

func (*WsServer) GetConnectionManager added in v1.1.0

func (s *WsServer) GetConnectionManager() *ConnectionManager

GetConnectionManager 获取连接管理器(用于健康检查等操作)

func (*WsServer) GetMetrics added in v1.1.0

func (s *WsServer) GetMetrics() *WebSocketMetrics

GetMetrics 获取监控指标快照(所有计数器均用 atomic 读取)

func (*WsServer) LogMetrics added in v1.1.0

func (s *WsServer) LogMetrics()

LogMetrics 记录当前监控指标到日志

func (*WsServer) NewPool added in v1.0.146

func (s *WsServer) NewPool(maxConn, limit, bucket, ping int) error

maxConn = 300 // 允许的最大并发连接数 limit = 20 // 每秒允许的平均消息数(令牌桶速率) bucket = 100 // 令牌桶容量(突发消息缓冲) ping = 15 // 心跳间隔(秒)

func (*WsServer) SetBroadcastKey added in v1.1.5

func (s *WsServer) SetBroadcastKey(key string)

SetBroadcastKey 广播数据密钥

func (*WsServer) SetIdleTimeout added in v1.1.0

func (s *WsServer) SetIdleTimeout(timeout time.Duration)

SetIdleTimeout 设置连接空闲超时时间

func (*WsServer) SetMaxBodyLen added in v1.1.6

func (s *WsServer) SetMaxBodyLen(n int)

SetMaxBodyLen 设置单条消息体最大长度(字节),需在 StartWebsocket 前调用;若已创建 Server 则同步更新 MaxRequestBodySize

func (*WsServer) SetValidateTokenPerMessage added in v1.1.6

func (s *WsServer) SetValidateTokenPerMessage(validate bool)

SetValidateTokenPerMessage 设置是否在每条消息时校验 token 有效期(validWebSocketBody 内生效)。 false(默认):仅建连时校验,连接期间 token 过期不踢线,性能更好; true:每条消息校验 exp,过期即 401,适合强安全/合规场景。

func (*WsServer) StartWebsocket added in v1.0.146

func (s *WsServer) StartWebsocket(addr string) error

func (*WsServer) StopWebsocket added in v1.1.0

func (s *WsServer) StopWebsocket() error

StopWebsocket 停止WebSocket服务器

func (*WsServer) StopWebsocketWithTimeout added in v1.1.0

func (s *WsServer) StopWebsocketWithTimeout(timeout time.Duration) error

StopWebsocketWithTimeout 带超时的优雅关闭

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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