simplerate

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 4 Imported by: 0

README

simplerate

simplerate is a small, in-memory rate limiter for Go. It limits how often an action can be performed within a given time interval.

Installation

Replace the module path with your own repository if needed.

go get github.com/aredoff/simplerate

Usage

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/aredoff/simplerate"
)

func main() {
	// Allow up to 5 events per second.
	lim := simplerate.New(5, time.Second)

	for i := 0; i < 10; i++ {
		lim.Wait()
		fmt.Println("event", i)
	}
}

API

  • New(limit int, interval time.Duration) Limiter
    Creates a new limiter that allows up to limit events per interval.

  • Limiter.Try() (ok bool, remaining time.Duration)
    Attempts to perform an action. Returns true if allowed, or false and the remaining time until the next action is allowed.

  • Limiter.Wait()
    Blocks until the action is allowed.

  • Limiter.WaitWithContext(ctx context.Context) error
    Blocks until the action is allowed or the context is canceled.

Notes

  • This limiter is in-memory and not distributed.
  • It is safe for concurrent use from multiple goroutines.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter interface {
	Wait()
	WaitWithContext(ctx context.Context) error
	Try() (ok bool, remaining time.Duration)
}

Limiter limits how often an action can be performed within a given time interval.

func New

func New(limit int, interval time.Duration) Limiter

New creates a new rate limiter for the limit and interval.

Jump to

Keyboard shortcuts

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