ratelimit

package
v0.25.3 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultAlertEmailTemplate = `` /* 8021-byte string literal not displayed */

DefaultAlertEmailTemplate 默认预警邮件HTML模板

View Source
const DefaultBlockEmailTemplate = `` /* 10008-byte string literal not displayed */

DefaultBlockEmailTemplate 默认封禁邮件HTML模板

Variables

This section is empty.

Functions

This section is empty.

Types

type EmailAlertConfig

type EmailAlertConfig struct {
	// 基础配置
	Enabled     bool     `mapstructure:"enabled" yaml:"enabled" json:"enabled"`             // 是否启用邮件预警
	To          []string `mapstructure:"to" yaml:"to" json:"to"`                            // 收件人列表
	CC          []string `mapstructure:"cc" yaml:"cc" json:"cc"`                            // 抄送列表
	AppName     string   `mapstructure:"app-name" yaml:"app-name" json:"appName"`           // 应用名称
	Environment string   `mapstructure:"environment" yaml:"environment" json:"environment"` // 环境标识 (dev/staging/prod)

	// 预警主题配置
	SubjectAlert string `mapstructure:"subject-alert" yaml:"subject-alert" json:"subjectAlert"` // 预警邮件主题
	SubjectBlock string `mapstructure:"subject-block" yaml:"subject-block" json:"subjectBlock"` // 封禁邮件主题

	// HTML模板配置
	TemplateAlert string `mapstructure:"template-alert" yaml:"template-alert" json:"templateAlert"` // 预警邮件HTML模板
	TemplateBlock string `mapstructure:"template-block" yaml:"template-block" json:"templateBlock"` // 封禁邮件HTML模板

	// 高级配置
	CooldownMinutes  int `mapstructure:"cooldown-minutes" yaml:"cooldown-minutes" json:"cooldownMinutes"`        // 冷却时间(分钟),避免频繁发送相同告警
	MaxAlertsPerHour int `mapstructure:"max-alerts-per-hour" yaml:"max-alerts-per-hour" json:"maxAlertsPerHour"` // 每小时最大告警数

	// 联系人配置
	SupportEmail  string `mapstructure:"support-email" yaml:"support-email" json:"supportEmail"`    // 技术支持邮箱
	SecurityEmail string `mapstructure:"security-email" yaml:"security-email" json:"securityEmail"` // 安全团队邮箱
}

EmailAlertConfig SMTP邮件预警配置

func DefaultEmailAlertConfig

func DefaultEmailAlertConfig() *EmailAlertConfig

DefaultEmailAlertConfig 返回默认邮件预警配置

type IPRule

type IPRule struct {
	IP       string     `mapstructure:"ip" yaml:"ip" json:"ip"`                   // IP地址(支持CIDR)
	Limit    *LimitRule `mapstructure:"limit" yaml:"limit" json:"limit"`          // 限流规则
	Type     string     `mapstructure:"type" yaml:"type" json:"type"`             // 类型: whitelist, blacklist, custom
	Priority int        `mapstructure:"priority" yaml:"priority" json:"priority"` // 优先级
}

IPRule IP限流规则

type LimitRule

type LimitRule struct {
	RequestsPerSecond int           `mapstructure:"requests-per-second" yaml:"requests-per-second" json:"requestsPerSecond"` // 每秒请求数
	BurstSize         int           `mapstructure:"burst-size" yaml:"burst-size" json:"burstSize"`                           // 突发大小
	WindowSize        time.Duration `mapstructure:"window-size" yaml:"window-size" json:"windowSize"`                        // 时间窗口
	BlockDuration     time.Duration `mapstructure:"block-duration" yaml:"block-duration" json:"blockDuration"`               // 阻塞时长
}

LimitRule 限流规则

type RateLimit

type RateLimit struct {
	ModuleName        string            `mapstructure:"module-name" yaml:"module-name" json:"moduleName"`                        // 模块名称
	Enabled           bool              `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                                   // 是否启用
	Strategy          Strategy          `mapstructure:"strategy" yaml:"strategy" json:"strategy"`                                // 限流策略
	DefaultScope      Scope             `mapstructure:"default-scope" yaml:"default-scope" json:"defaultScope"`                  // 默认作用域
	GlobalLimit       *LimitRule        `mapstructure:"global-limit" yaml:"global-limit" json:"globalLimit"`                     // 全局限流规则
	Routes            []RouteLimit      `mapstructure:"routes" yaml:"routes" json:"routes"`                                      // 路由级别限流
	IPRules           []IPRule          `mapstructure:"ip-rules" yaml:"ip-rules" json:"ipRules"`                                 // IP规则
	UserRules         []UserRule        `mapstructure:"user-rules" yaml:"user-rules" json:"userRules"`                           // 用户规则
	Storage           StorageConfig     `mapstructure:"storage" yaml:"storage" json:"storage"`                                   // 存储配置
	CustomRuleLoader  string            `mapstructure:"custom-rule-loader" yaml:"custom-rule-loader" json:"customRuleLoader"`    // 自定义规则加载器名称
	EnableDynamicRule bool              `mapstructure:"enable-dynamic-rule" yaml:"enable-dynamic-rule" json:"enableDynamicRule"` // 是否启用动态规则
	EmailAlertConfig  *EmailAlertConfig `mapstructure:"email-alert-config" yaml:"email-alert-config" json:"emailAlertConfig"`    // 邮件告警配置名称
}

RateLimit 增强限流配置

func Default

func Default() *RateLimit

Default 默认限流配置

func (*RateLimit) AddIPRule

func (r *RateLimit) AddIPRule(rule IPRule) *RateLimit

AddIPRule 添加IP规则

func (*RateLimit) AddRouteLimit

func (r *RateLimit) AddRouteLimit(route RouteLimit) *RateLimit

AddRouteLimit 添加路由限流

func (*RateLimit) AddUserRule

func (r *RateLimit) AddUserRule(rule UserRule) *RateLimit

AddUserRule 添加用户规则

func (*RateLimit) Clone

func (r *RateLimit) Clone() internal.Configurable

Clone 返回配置副本

func (*RateLimit) Disable

func (r *RateLimit) Disable() *RateLimit

Disable 禁用限流中间件

func (*RateLimit) Enable

func (r *RateLimit) Enable() *RateLimit

Enable 启用限流中间件

func (*RateLimit) EnableDynamic

func (r *RateLimit) EnableDynamic() *RateLimit

EnableDynamic 启用动态规则

func (*RateLimit) Get

func (r *RateLimit) Get() interface{}

Get 返回配置

func (*RateLimit) IsEnabled

func (r *RateLimit) IsEnabled() bool

IsEnabled 检查是否启用

func (*RateLimit) Set

func (r *RateLimit) Set(data interface{})

Set 设置配置

func (*RateLimit) Validate

func (r *RateLimit) Validate() error

Validate 验证配置

func (*RateLimit) WithCustomLoader

func (r *RateLimit) WithCustomLoader(loaderName string) *RateLimit

WithCustomLoader 设置自定义加载器

func (*RateLimit) WithGlobalLimit

func (r *RateLimit) WithGlobalLimit(limit *LimitRule) *RateLimit

WithGlobalLimit 设置全局限流

func (*RateLimit) WithStorage

func (r *RateLimit) WithStorage(storage StorageConfig) *RateLimit

WithStorage 设置存储配置

func (*RateLimit) WithStrategy

func (r *RateLimit) WithStrategy(strategy Strategy) *RateLimit

WithStrategy 设置限流策略

type RedisStorage

type RedisStorage struct {
	Addresses    []string      `mapstructure:"addresses" yaml:"addresses" json:"addresses"`              // Redis地址
	Password     string        `mapstructure:"password" yaml:"password" json:"password"`                 // 密码
	DB           int           `mapstructure:"db" yaml:"db" json:"db"`                                   // 数据库
	PoolSize     int           `mapstructure:"pool-size" yaml:"pool-size" json:"poolSize"`               // 连接池
	MinIdleConns int           `mapstructure:"min-idle-conns" yaml:"min-idle-conns" json:"minIdleConns"` // 最小空闲连接
	MaxRetries   int           `mapstructure:"max-retries" yaml:"max-retries" json:"maxRetries"`         // 最大重试
	ReadTimeout  time.Duration `mapstructure:"read-timeout" yaml:"read-timeout" json:"readTimeout"`      // 读超时
	WriteTimeout time.Duration `mapstructure:"write-timeout" yaml:"write-timeout" json:"writeTimeout"`   // 写超时
	ClusterMode  bool          `mapstructure:"cluster-mode" yaml:"cluster-mode" json:"clusterMode"`      // 集群模式
}

RedisStorage Redis存储配置(复用cache.Redis字段)

type RouteLimit

type RouteLimit struct {
	Path      string     `mapstructure:"path" yaml:"path" json:"path"`                // 路由路径(支持通配符)
	Methods   []string   `mapstructure:"methods" yaml:"methods" json:"methods"`       // HTTP方法
	Limit     *LimitRule `mapstructure:"limit" yaml:"limit" json:"limit"`             // 限流规则
	PerUser   bool       `mapstructure:"per-user" yaml:"per-user" json:"perUser"`     // 是否按用户限流
	PerIP     bool       `mapstructure:"per-ip" yaml:"per-ip" json:"perIp"`           // 是否按IP限流
	Whitelist []string   `mapstructure:"whitelist" yaml:"whitelist" json:"whitelist"` // 白名单
	Blacklist []string   `mapstructure:"blacklist" yaml:"blacklist" json:"blacklist"` // 黑名单
}

RouteLimit 路由级别限流

type Scope

type Scope string

Scope 限流作用域

const (
	ScopeGlobal   Scope = "global"    // 全局限流
	ScopePerIP    Scope = "per-ip"    // 按IP限流
	ScopePerUser  Scope = "per-user"  // 按用户限流
	ScopePerRoute Scope = "per-route" // 按路由限流
)

type StorageConfig

type StorageConfig struct {
	Type          string        `mapstructure:"type" yaml:"type" json:"type"`                              // 存储类型: memory, redis
	KeyPrefix     string        `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"`             // Key前缀
	CleanInterval time.Duration `mapstructure:"clean-interval" yaml:"clean-interval" json:"cleanInterval"` // 清理间隔
	RedisConfig   *RedisStorage `mapstructure:"redis" yaml:"redis" json:"redis"`                           // Redis配置(可选)
}

StorageConfig 存储配置

type Strategy

type Strategy string

Strategy 限流策略类型

const (
	StrategyTokenBucket   Strategy = "token-bucket"   // 令牌桶算法
	StrategyLeakyBucket   Strategy = "leaky-bucket"   // 漏桶算法
	StrategySlidingWindow Strategy = "sliding-window" // 滑动窗口
	StrategyFixedWindow   Strategy = "fixed-window"   // 固定窗口
)

type UserRule

type UserRule struct {
	UserID   string     `mapstructure:"user-id" yaml:"user-id" json:"userId"`       // 用户ID(支持通配符)
	UserType string     `mapstructure:"user-type" yaml:"user-type" json:"userType"` // 用户类型
	Role     string     `mapstructure:"role" yaml:"role" json:"role"`               // 用户角色
	Limit    *LimitRule `mapstructure:"limit" yaml:"limit" json:"limit"`            // 限流规则
	Priority int        `mapstructure:"priority" yaml:"priority" json:"priority"`   // 优先级
}

UserRule 用户限流规则

Jump to

Keyboard shortcuts

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