ratelimit

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2020 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

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

store := NewMemory(...)
srv := NewServer(store)
h = srv.RateLimit(h, logs.ERROR())

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 Server

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

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

func NewServer

func NewServer(store Store, capacity int64, rate time.Duration, fn GenFunc) *Server

NewServer 声明一个新的 Server rate 拿令牌的频率 fn 为令牌桶名称的产生方法,默认为用户的访问 IP。

func (*Server) RateLimit

func (srv *Server) RateLimit(h http.Handler, errlog *log.Logger) http.Handler

RateLimit 限制单一用户的 HTTP 请求数量。会向报头输出以下内容:

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

func (*Server) Transfer

func (srv *Server) 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