grate

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2021 License: MIT Imports: 4 Imported by: 0

README

grate

Grate is simple rate limit middleware for Go.

Usage

package main

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/gladmo/grate"
)

func main() {
	// new rate limiter with ttl
	lim := grate.NewRateLimiter(1, 1, time.Second*10)

	var wg sync.WaitGroup

	// Limit for each key
	for i := 0; i < 100; i++ {
		wg.Add(1)

		go func(key string) {
			defer wg.Done()

			// each key allot a *rate.Limiter
			err := lim.Wait(key, context.Background())
			if err != nil {
				panic(err)
			}

			fmt.Println(fmt.Sprintf("idx:%s, now: %s", key, time.Now()))

		}(fmt.Sprint(i % 3))
	}

	wg.Wait()
}
gin middleware
package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gladmo/grate"
	gingrate "github.com/gladmo/grate/gin-grate"
)

func main() {
	r := gin.Default()

	// use gin grate ip limiter
	r.Use(gingrate.IPLimiter(grate.NewRateLimiter(10, 1, time.Minute)))
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "ok")
	})

	err := r.Run("0.0.0.0:8910")
	if err != nil {
		panic(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RateLimiter

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

RateLimiter rate limiter with ttl

func NewRateLimiter

func NewRateLimiter(bursts int, limit rate.Limit, ttl time.Duration) *RateLimiter

NewRateLimiter create rate limiter with ttl, every *rate.Limiter allows events up to rate limit and permits bursts of at most b tokens.

func (RateLimiter) Allow

func (th RateLimiter) Allow(item string) bool

Allow is shorthand for getLimiter(item).Allow().

func (RateLimiter) OnEvicted

func (th RateLimiter) OnEvicted(fn func(item string, lim *rate.Limiter))

OnEvicted a callback function called when lim is purged from the cache.

func (RateLimiter) Remove

func (th RateLimiter) Remove(item string)

Remove rate.Limiter

func (RateLimiter) Reserve

func (th RateLimiter) Reserve(item string) *rate.Reservation

Reserve is shorthand for getLimiter(item).Reserve().

func (RateLimiter) Wait

func (th RateLimiter) Wait(item string, ctx context.Context) error

Wait is shorthand for getLimiter(item).Wait(ctx).

Directories

Path Synopsis
gin

Jump to

Keyboard shortcuts

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