rateio

package module
v0.0.0-...-4627271 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: MIT Imports: 3 Imported by: 15 modules, 26 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rateio provides an io interfaces for rate-limiting.

This can be used to apply rate limiting to any type that implements an io-style interface.

For example, we can use it to restrict the reading rate of a net.Conn:

type limitedConn struct {
	net.Conn
	io.Reader // Our rate-limited io.Reader for net.Conn
}

func (r *limitedConn) Read(p []byte) (n int, err error) {
	return r.Reader.Read(p)
}

// ReadLimitConn returns a net.Conn whose io.Reader interface is rate-limited by limiter.
func ReadLimitConn(conn net.Conn, limiter rateio.Limiter) net.Conn {
	return &limitedConn{
		Conn:   conn,
		Reader: rateio.NewReader(conn, limiter),
	}
}

Then we can use ReadLimitConn to wrap our existing net.Conn and continue using the wrapped version in its place.

Index

Constants

This section is empty.

Variables

View Source
var ErrRateExceeded = errors.New("Read rate exceeded.")

ErrRateExceeded is the error returned when the read rate exceeds our specification.

Functions

func NewGracefulLimiter

func NewGracefulLimiter(amount int, frequency time.Duration, grace time.Duration) *simpleLimiter

NewGracefulLimiter returns a Limiter that is the same as a SimpleLimiter but adds a grace period at the start of the rate limiting where it allows unlimited bytes to be read during that period.

func NewReader

func NewReader(r io.Reader, limiter Limiter) io.Reader

NewReader proxies an io.Reader but keeps track of bytes read based on our Limiter.

func NewSimpleLimiter

func NewSimpleLimiter(amount int, frequency time.Duration) *simpleLimiter

NewSimpleLimiter creates a Limiter that restricts a given number of bytes per frequency.

func NewWriter

func NewWriter(w io.Writer, limiter Limiter) io.Writer

NewWriter proxies an io.Writer but keeps track of bytes read based on our Limiter.

Types

type Limiter

type Limiter interface {
	// Apply this many bytes to the limiter, return ErrRateExceeded if the defined rate is exceeded.
	Count(int) error
}

Limiter is an interface for a rate limiter. There are a few example limiters included in the package, but feel free to go wild with your own.

Jump to

Keyboard shortcuts

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