ratelimit

package
v5.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2022 License: MIT Imports: 7 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 cache.Cache, 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

Jump to

Keyboard shortcuts

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