Smart rate limiter middleware for Gear, base on redis or memory limiter.
go get github.com/teambition/gear-ratelimiter
import "github.com/teambition/gear-ratelimiter"
import (
"github.com/teambition/gear-ratelimiter"
redisClient "github.com/teambition/gear-ratelimiter/redis"
"github.com/go-redis/redis"
)
limiter := ratelimiter.New(&ratelimiter.Options{
Client: redisClient.NewRedisClient(&redis.Options{Addr: "127.0.0.1:6379"})
GetID: func(ctx *gear.Context) string {
return "user-123465"
},
Max: 10,
Duration: time.Minute, // limit to 1000 requests in 1 minute.
Policy: map[string][]int{
"/": []int{16, 6 * 1000},
"GET /a": []int{3, 5 * 1000, 10, 60 * 1000},
"GET /b": []int{5, 60 * 1000},
"/c": []int{6, 60 * 1000},
},
})
app.UseHandler(limiter)
returns a Gear middleware handler.
options.Client
: Optional, a wrapped redis client. if omit, it will use memory limiter.options.Max
: Optional, Type:int
, The max count in duration and using it when limiter cannot found the appropriate policy, default to100
.options.Prefix
: Optional, Type:String
, redis key namespace, default toLIMIT
.options.Duration
: Optional, {Number}, of limit in milliseconds, default to3600000
options.GetID
: Optional, {Function}, generate a identifier for requests, default to user's IPoptions.Policy
: Required, {map[string][]int}, limit policy
Try into github.com/teambition/gear-ratelimiter directory:
go run example/main.go
Gear-Ratelimiter is licensed under the MIT license. Copyright © 2016-2017 Teambition.