rate

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: MIT Imports: 4 Imported by: 6

README

Rate

Package rate provides a rate limiter. It implements a classic token bucket algorithm, which can achieve functions such as http api speed limit and network bandwidth speed limit.

Documentation

Overview

Package rate provides a rate limiter. It implements a classic token bucket algorithm, which can achieve functions such as http api speed limit and network bandwidth speed limit.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limits

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

Limits represents a rate limiter that controls resource allocation over time.

func NewLimits

func NewLimits(r uint64, p time.Duration) *Limits

NewLimits creates a new rate limiter with rate r over period p.

Overflow warning: If the rate r is set to a very large value (e.g., 1G = 1024 * 1024 * 1024) and the period (p) is one second, the internal counters may overflow after approximately 544 years. However, this overflow only occurs if the limiter remains completely idle (i.e., neither peek nor wait is called) for the entire duration. Consider this when designing long-running systems with very high rates.

func (*Limits) Peek

func (l *Limits) Peek(n uint64) bool

Peek glances there are enough resources (n) available.

func (*Limits) Wait

func (l *Limits) Wait(n uint64)

Wait ensures there are enough resources (n) available, blocking if necessary.

type LimitsWriter added in v1.0.6

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

LimitsWriter is an io.Writer that applies rate limiting to write operations.

For example, to limit a reader's read speed to 1MB/s:

reader := io.TeeReader(os.Stdin, NewLimitsWriter(1024*1024, time.Second))

Or, to limit a writer's write speed to 1MB/s:

writer := io.MultiWriter(os.Stdout, NewLimitsWriter(1024*1024, time.Second))

func NewLimitsWriter added in v1.0.6

func NewLimitsWriter(r uint64, p time.Duration) *LimitsWriter

NewLimitsWriter creates a new LimitsWriter that limits write operations to r bytes per period p.

func (*LimitsWriter) Write added in v1.0.6

func (l *LimitsWriter) Write(p []byte) (int, error)

Write writes data to the underlying writer, applying rate limiting based on the configured limits.

Directories

Path Synopsis
cmd
race command

Jump to

Keyboard shortcuts

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