Socket
Book a DemoInstallSign in
Socket

nikand.dev/go/rate

Package Overview
Dependencies
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nikand.dev/go/rate

Go Modules
Version
v0.2.0
Version published
Created
Source

Documentation Go workflow CircleCI codecov Go Report Card GitHub tag (latest SemVer)

Rate limiter

Token bucket rate limiter.

Usage

Create limiter

l := rate.NewLimiter(time.Now(),
	1000 / time.Second.Seconds(), // 1000 tokens per second
	2000, // 2000 tokens burst
	)

// smooth 1KB per second with at most 128 bytes at a time
l = rate.NewLimiter(time.Now(),
	1000 / time.Second.Seconds(),
	128)

// 3 MB per minute allowing to spend it all at once
l = rate.NewLimiter(time.Now(),
	3000000 / time.Minute.Seconds(),
	3000000)

Take or drop

func (c *Conn) Write(p []byte) (int, error) {
	if !l.Take(time.Now(), len(p)) {
		return 0, ErrLimited
	}

	return c.Conn.Write(p)
}

Borrow and wait

func (c *Conn) Write(p []byte) (int, error) {
	delay := l.Borrow(time.Now(), len(p))

	if delay != 0 {
		time.Sleep(delay)
	}

	return c.Conn.Write(p)
}

Write as much as we can

func (c *Conn) Write(p []byte) (int, error) {
	now := time.Now()

	val := l.Value(now)

	n := int(val)
	if n > len(p) {
		n = len(p)
	}

	_ = l.Take(now, float64(n)) // must be true

	n, err := c.Conn.Write(p[:n])
	if err != nil {
		return n, err
	}
	if n != len(p) {
		err = ErrLimited
	}

	return n, err
}

FAQs

Package last updated on 11 Nov 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts