httpsvr

package
v1.1.34 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 33 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"

	// HKDF info:历史常量名含 ecdh,勿改字符串以免与已部署客户端派生密钥不一致
	SharedInfo = "freego-ecdh-aes-gcm"
)

Variables

View Source
var (
	MAX_BODY_LEN  = 200000 // 最大参数值长度
	MAX_TOKEN_LEN = 2048   // JWT 等常规 Authorization 上限;Plan2 见 maxAuthorizationHeaderLen
	MAX_CODE_LEN  = 1024   // 最大Code值长度
)

Functions

func ErrorMsgToLang

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

func NewGracefulListener

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

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

func RemoteIPFromRequest

func RemoteIPFromRequest(r *http.Request) string

RemoteIPFromRequest 从标准 http.Request 安全获取真实客户端 IP(与 Context.RemoteIP 规则一致)。

Types

type CacheAware

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

type Configs

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

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

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   *wire.JsonBody       // 8字节 - 指针
	Response   *Response            // 8字节 - 指针

	RouterConfig *RouterConfig // 8字节 - 指针

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

	// 8字节其他字段组 (2个字段)
	Storage map[string]interface{}
	// 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

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

func (*Context) CheckOuterSign

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

CheckOuterSign 校验外层数字签名(经 cipher.Verify;ML-DSA-87)。

func (*Context) ClientDevice

func (self *Context) ClientDevice() string

func (*Context) ClientLanguage

func (self *Context) ClientLanguage() string

func (*Context) CreatePublicKey

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

func (*Context) DelStorage

func (self *Context) DelStorage(k string)

func (*Context) GetCacheObject

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

func (*Context) GetHeader

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

func (self *Context) GetPostBody() string

func (*Context) GetRawTokenBytes

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) GetUserIDInt64

func (self *Context) GetUserIDInt64() int64

GetUserIDInt64 获取用户ID int64类型, 零值认为是无用户信息

func (*Context) GetUserIDString

func (self *Context) GetUserIDString() string

GetUserIDString 获取用户ID string类型

func (*Context) Handle

func (self *Context) Handle() error

func (*Context) Json

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

func (*Context) NoBody

func (self *Context) NoBody() error

func (*Context) Parser

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

func (*Context) RemoteIP

func (self *Context) RemoteIP() string

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

func (*Context) Text

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

type ErrorHandle

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

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

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

CloseWithTimeout 带超时的优雅关闭

type HookNode

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

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

filters:须在进程初始化阶段完成 AddFilter;StartServer 内会经 createFilterChain 整体替换为排序后的链。 约定:监听并处理请求期间不得再 AddFilter(无并发 append 与 DoFilter 遍历同一切片的安全保证)。

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) AddCipherHook

func (self *HttpNode) AddCipherHook(hook fwsign.CipherHook) error

AddCipherHook 注册 Plan2 Cipher 动态加载回调:按 usr 解析服务端私钥与客户端公钥并构造 ML-DSA Cipher。 与客户端 HttpSDK.SetMLDSA87Object 互为镜像;Plan0/Plan1 不使用外层 Valid 签名。

func (*HttpNode) AddErrorHandle

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

func (*HttpNode) AddFilter

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

AddFilter 追加自定义过滤器(按 Order 与内置过滤器合并排序见 StartServer 内 createFilterChain)。 使用约定:仅在服务监听前、初始化阶段调用;监听运行期间不得再调用,否则与并发请求执行 DoFilter 不安全。

func (*HttpNode) AddJwtConfig

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

func (*HttpNode) AddLanguage

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

func (*HttpNode) AddLanguageByJson

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

func (*HttpNode) AddLocalCache

func (self *HttpNode) AddLocalCache(cacheAware CacheAware)

AddLocalCache 增加本地缓存实例

func (*HttpNode) AddRedisCache

func (self *HttpNode) AddRedisCache(cacheAware CacheAware)

AddRedisCache 增加redis缓存实例

func (*HttpNode) AddRoleRealm

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

func (*HttpNode) Bytes

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

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

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) SetAcceptTimeout

func (self *HttpNode) SetAcceptTimeout(timeout int64)

func (*HttpNode) SetDefaultMethodRateLimiter

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

func (*HttpNode) SetDynamicSecretKey

func (self *HttpNode) SetDynamicSecretKey(key string)

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

func (*HttpNode) SetGatewayRateLimiter

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

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

func (*HttpNode) SetLengthCheck

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

func (*HttpNode) SetMethodRateLimiterByPath

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

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

func (*HttpNode) SetSystem

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

func (*HttpNode) SetUserRateLimiter

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

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

func (*HttpNode) StartServer

func (self *HttpNode) StartServer(addr string)

func (*HttpNode) Text

func (self *HttpNode) Text(ctx *Context, data string) 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 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 RouterConfig

type RouterConfig struct {
	Guest       bool // 游客模式,原始请求 false.否 true.是 - 1字节
	UsePlan2    bool // Plan2 匿名路由(ML-KEM+ML-DSA) false.否 true.是 - 1字节
	KeyRoute    bool // WebSocket plan2 key 路由(仅允许匿名 plan0)
	LoginRoute  bool // WebSocket plan2 login 路由(仅允许 plan2)
	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

type System struct {
	Name          string // 系统名
	Version       string // 系统版本
	AcceptTimeout int64  // 超时主动断开客户端连接,秒
}

System 结构体

type UserRateLimiterFilter

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

func (*UserRateLimiterFilter) DoFilter

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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