ratelimit

package
v2.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2020 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package ratelimit 提供了 X-Rate-Limit 功能的中间件

X-Rate-Limit-Limit: 同一个时间段所允许的请求的最大数目;
X-Rate-Limit-Remaining: 在当前时间段内剩余的请求的数量;
X-Rate-Limit-Reset: 为了得到最大请求数所等待的秒数。

store := NewMemory(...)
srv := New(store)
h = srv.Middleware(h)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenIP

func GenIP(r *http.Request) (string, error)

GenIP 用于生成区分令牌桶的 IP 地址

Types

type Bucket

type Bucket struct {
	Capacity int64         `json:"cap"`    // 上限
	Rate     time.Duration `json:"rate"`   // 每隔 rate 添加一个令牌
	Tokens   int64         `json:"tokens"` // 可用令牌数量
	Last     time.Time     `json:"last"`   // 最后次添加令牌的时间
}

Bucket 令牌桶

真正的令牌桶算法应该是按时自动增加令牌数量, 此处稍作修改:去掉自动分发令牌功能,集中在每次拿令牌时, 一次性补全之前缺的令牌数量。

type GenFunc

type GenFunc func(*http.Request) (string, error)

GenFunc 用于生成用户唯一 ID 的函数,用于区分令牌桶所属的用户

type Ratelimit

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

Ratelimit 提供操作 Bucket 的一系列服务

func New

func New(store Store, capacity int64, rate time.Duration, fn GenFunc, errlog *log.Logger) *Ratelimit

New 声明一个新的 Ratelimit

rate 拿令牌的频率 fn 为令牌桶名称的产生方法,默认为用户的访问 IP。

func (*Ratelimit) Middleware

func (rate *Ratelimit) Middleware(next http.Handler) http.Handler

Middleware 将当前中间件应用于 next

func (*Ratelimit) MiddlewareFunc

func (rate *Ratelimit) MiddlewareFunc(next func(w http.ResponseWriter, r *http.Request)) http.Handler

MiddlewareFunc 将当前中间件应用于 next

func (*Ratelimit) Transfer

func (rate *Ratelimit) Transfer(oldName, newName string) error

Transfer 将 oldName 的数据传送给 newName

type Store

type Store interface {
	// 设置或是添加指定名称的令牌桶
	Set(name string, val *Bucket) error

	// 删除指定的令牌桶
	Delete(name string) error

	// 获取指定的令牌桶,为空则返回 nil
	Get(name string) *Bucket
}

Store 存储 Bucket 的接口

func NewMemcache

func NewMemcache(prefix string, client *gm.Client, expiration int32, errlog *log.Logger) Store

NewMemcache 声明一个以 memcache 为存储介质的 Store

prefix 变量名的统一前缀,防止与其它变量名冲突 client memcached 客户端实例。 expiration 过期时间,单位:秒。 errlog 错误时,写的日志记录。

func NewMemory

func NewMemory(capacity int64) Store

NewMemory 声明一个内存类型的 Store

Jump to

Keyboard shortcuts

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