Skip to content
This repository has been archived by the owner on Feb 8, 2023. It is now read-only.

alibaba-archive/gear-ratelimiter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gear-Ratelimiter

Smart rate limiter middleware for Gear, base on redis or memory limiter.

Build Status Coverage Status License GoDoc

Installation

go get github.com/teambition/gear-ratelimiter
import "github.com/teambition/gear-ratelimiter"

Demo

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)

API

ratelimiter.New(ratelimiter.Options)

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 to 100.
  • options.Prefix: Optional, Type: String, redis key namespace, default to LIMIT.
  • options.Duration: Optional, {Number}, of limit in milliseconds, default to 3600000
  • options.GetID: Optional, {Function}, generate a identifier for requests, default to user's IP
  • options.Policy: Required, {map[string][]int}, limit policy

Example

Try into github.com/teambition/gear-ratelimiter directory:

go run example/main.go

License

Gear-Ratelimiter is licensed under the MIT license. Copyright © 2016-2017 Teambition.

About

Smart rate limiter middleware for Gear, base on redis or memory limiter.

Resources

License

Stars

Watchers

Forks

Packages

No packages published