freqlimit

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2022 License: MIT Imports: 4 Imported by: 0

README

freqlimit

A tiny library to limit the request frequency based on redis

Installation
go get github.com/daqiancode/freqlimit
Example
// add frequency limit for user/1
limit := freqlimit.NewFreqLimit(getRedisClient(), "user/1")
// add freq limit < 2 times/1 seconds
limit.AddLimit(1, 2)
// add freq limit < 100 times/60 seconds
limit.AddLimit(60, 100)

ok, err:= limit.Incr()
if err!=nil {
    return err
}
if !ok {
    return errors.New("exceed the request frequency")
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultExpireDelay = 10
)

Functions

This section is empty.

Types

type FreqLimit

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

func NewFreqLimit

func NewFreqLimit(client *redis.Client, key string) *FreqLimit

func (*FreqLimit) AddLimit

func (s *FreqLimit) AddLimit(window, max int64)

AddLimit windows: window length in seconds , max: max request count

func (*FreqLimit) GetLeft

func (s *FreqLimit) GetLeft() (map[int64]int64, error)

GetLeft return all window rest request count, window:left

func (*FreqLimit) Incr

func (s *FreqLimit) Incr() (bool, error)

Incr increase the number of calls, throw error if exceed the max call number. return true if under frequency limit,return false if exceed the frequency limit

func (*FreqLimit) SetCtx

func (s *FreqLimit) SetCtx(ctx context.Context)

SetCtx set context for redis API

type Limit

type Limit struct {
	Window int64
	Max    int64
}

Jump to

Keyboard shortcuts

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