ratelimit

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2022 License: MIT Imports: 3 Imported by: 156

README

ratelimit

License Go version Release Checks GoDoc

A Golang rate limit implementation which allows burst of request during the defined duration.

Example

An Example showing usage of ratelimit as a library is specified below:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/projectdiscovery/ratelimit"
)

func main() {

	// create a rate limiter by passing context, max tasks/requests , time interval
	limiter := ratelimit.New(context.Background(), 5, time.Duration(10*time.Second))

	save := time.Now()

	for i := 0; i < 10; i++ {
		// run limiter.Take() method before each task
		limiter.Take()
		fmt.Printf("Task %v completed after %v\n", i, time.Since(save))
	}

	/*
		Output:
		Task 0 completed after 4.083µs
		Task 1 completed after 111.416µs
		Task 2 completed after 118µs
		Task 3 completed after 121.083µs
		Task 4 completed after 124.583µs
		Task 5 completed after 10.001356375s
		Task 6 completed after 10.001524791s
		Task 7 completed after 10.001537583s
		Task 8 completed after 10.001542708s
		Task 9 completed after 10.001548666s
	*/
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

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

Limiter allows a burst of request during the defined duration

func New

func New(ctx context.Context, max uint, duration time.Duration) *Limiter

New creates a new limiter instance with the tokens amount and the interval

func NewUnlimited

func NewUnlimited(ctx context.Context) *Limiter

NewUnlimited create a bucket with approximated unlimited tokens

func (*Limiter) Take

func (rateLimiter *Limiter) Take()

Take one token from the bucket

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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