Code Monkey home page Code Monkey logo

ratelimiter-go's Introduction

ratelimiter-go

The fastest abstract rate limiter, base on memory or redis storage.

Build Status Coverage Status License GoDoc

Features

  • Distributed
  • Atomicity
  • High-performance
  • Support redis cluster
  • Support memory storage

Installation

go get github.com/teambition/ratelimiter-go

HTTP Server Demo

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

go run example/main.go

Visit: http://127.0.0.1:8080/

package main

import (
	"fmt"
	"html"
	"log"
	"net/http"
	"strconv"
	"time"

	ratelimiter "github.com/teambition/ratelimiter-go"
	redis "github.com/go-redis/redis"
)

// Implements RedisClient for redis.Client
type redisClient struct {
	*redis.Client
}

func (c *redisClient) RateDel(key string) error {
	return c.Del(key).Err()
}
func (c *redisClient) RateEvalSha(sha1 string, keys []string, args ...interface{}) (interface{}, error) {
	return c.EvalSha(sha1, keys, args...).Result()
}
func (c *redisClient) RateScriptLoad(script string) (string, error) {
	return c.ScriptLoad(script).Result()
}

func main() {
	// use memory
	// limiter := ratelimiter.New(ratelimiter.Options{
	// 	Max:      10,
	// 	Duration: time.Minute, // limit to 1000 requests in 1 minute.
	// })

	// or use redis
	client := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	limiter := ratelimiter.New(ratelimiter.Options{
		Max:      10,
		Duration: time.Minute, // limit to 1000 requests in 1 minute.
		Client:   &redisClient{client},
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		res, err := limiter.Get(r.URL.Path)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}

		header := w.Header()
		header.Set("X-Ratelimit-Limit", strconv.FormatInt(int64(res.Total), 10))
		header.Set("X-Ratelimit-Remaining", strconv.FormatInt(int64(res.Remaining), 10))
		header.Set("X-Ratelimit-Reset", strconv.FormatInt(res.Reset.Unix(), 10))

		if res.Remaining >= 0 {
			w.WriteHeader(200)
			fmt.Fprintf(w, "Path: %q\n", html.EscapeString(r.URL.Path))
			fmt.Fprintf(w, "Remaining: %d\n", res.Remaining)
			fmt.Fprintf(w, "Total: %d\n", res.Total)
			fmt.Fprintf(w, "Duration: %v\n", res.Duration)
			fmt.Fprintf(w, "Reset: %v\n", res.Reset)
		} else {
			after := int64(res.Reset.Sub(time.Now())) / 1e9
			header.Set("Retry-After", strconv.FormatInt(after, 10))
			w.WriteHeader(429)
			fmt.Fprintf(w, "Rate limit exceeded, retry in %d seconds.\n", after)
		}
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Node.js version: thunk-ratelimiter

Documentation

The docs can be found at godoc.org, as usual.

License

ratelimiter-go is licensed under the MIT license. Copyright © 2016-2018 Teambition.

ratelimiter-go's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ratelimiter-go's Issues

Some doubts about readme

in readme

	limiter := ratelimiter.New(ratelimiter.Options{
		Max:      10,
		Duration: time.Minute, // limit to 1000 requests in 1 minute.
		Client:   &redisClient{client},
	})

why Max is 10 and comment said "limit to 1000"

How to limit request by second?

I'm trying to use this for limiting requests by second but it doesn't seem to work and all requests are blocked:

	limiter := ratelimiter.New(ratelimiter.Options{
		Max:      5,
		Duration: time.Second,
		Client:   &redisClient{client},
	})
	res, err := limiter.Get("test")
	if err != nil {
		log.Println(err)
		return
	}
	if res.Remaining < 1 {
		fmt.Printf("Blocked: %+v\n", res)
	} else {
		fmt.Printf("Allowed: %+v\n", res)
	}
	client := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	for i := 0; i < 1000; i++ {
		rateLimit("test", client)
		time.Sleep(100 * time.Millisecond)
	}
Blocked: {Total:60 Remaining:-1 Duration:1m0s Reset:2019-09-04 17:16:42.937 +0700 +07}
Blocked: {Total:60 Remaining:-1 Duration:1m0s Reset:2019-09-04 17:16:42.937 +0700 +07}
Blocked: {Total:60 Remaining:-1 Duration:1m0s Reset:2019-09-04 17:16:42.937 +0700 +07}
Blocked: {Total:60 Remaining:-1 Duration:1m0s Reset:2019-09-04 17:16:42.937 +0700 +07}
Blocked: {Total:60 Remaining:-1 Duration:1m0s Reset:2019-09-04 17:16:42.937 +0700 +07}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.