ratelimit

package
v2.33.13 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2023 License: MIT Imports: 11 Imported by: 0

README

Rate limit Middleware

Example usage

Create a webserver that limits the number of requests to 2 requests per minute on "GET /" Complete example can be found here

   func main() {
   	r := mux.NewRouter()
   	r.HandleFunc("/", HomeHandler)
   
   	limiter := ratelimit.CreateLimiter(ratelimit.GetRedisStore("localhost:6379"))
   	limiter.Configure(
   		ratelimit.Request{Method: http.MethodGet, Path: "/"},
   		func(request *http.Request) ([]ratelimit.Limit, error) {
   			return []ratelimit.Limit{{
   				RequestPerMinute: 2,
   				Key:              "/",
   			}}, nil
   
   		})
   	r.Use(limiter.Middleware())
   
   	err := http.ListenAndServe(":8080", r)
   	log.Errorf(err.Error())
   }

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Connection added in v2.11.0

type Connection interface {
	io.Closer

	Incr(key string) (int, error)
}

type ConnectionPool added in v2.11.0

type ConnectionPool interface {
	Connect() Connection
}

func GetRedisPool added in v2.11.0

func GetRedisPool(address string) ConnectionPool

type Limit

type Limit struct {
	RequestPerMinute int
	Key              string
}

type Limiter

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

func (*Limiter) Configure

func (l *Limiter) Configure(path Request, gen limitGenerator)

The LimitGenerator function should return the rate limit with corresponding key that should be used for the given path template path.pathTemplate should be the pathtemplate used to route the request

If you give multiple configs for 1 endpoint. The most restrictive one will apply

func (*Limiter) Middleware

func (l *Limiter) Middleware() mux.MiddlewareFunc

Rate limiting middleware, you can configure 1 or many limits for each path template using a limitGenerator The algorithm is inspired from: https://redislabs.com/redis-best-practices/basic-rate-limiting/

The key will be stored in clear text in the cache. If the key contains personal data please consider hashing the key

func (*Limiter) SetConnectionPool added in v2.11.0

func (l *Limiter) SetConnectionPool(p ConnectionPool) *Limiter

type Request

type Request struct {
	Method       string
	PathTemplate string
}

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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