limit

package module
v0.0.0-...-4f95397 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2021 License: MIT Imports: 4 Imported by: 0

README

GoDoc

limit

Go package limit provides a simple rate limiter for concurrent access.

Example middleware to limit HTTP requests:

import (
	"github.com/pmorjan/limit"
	"github.com/tomasen/realip"
)

func limitRequests(next http.Handler) http.Handler {
    userLimit,_ := limit.New(1, 10) // 1 request per second, burst 10

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ip := realip.FromRequest(r)
		if !userLimit.Allowed(ip) {
			http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
			return
		}
		next.ServeHTTP(w, r)
	})
}

Documentation

Overview

Package limit provides a simple rate limiter for concurrent access.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// MaxKeepRecords defines how long records are keept.
	MaxKeepRecords time.Duration = time.Minute * 5
	// ErrInvalidRate is returned to indicate an invalid rate.
	ErrInvalidRate error = errors.New("rate value too low")
)

Functions

This section is empty.

Types

type Limit

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

Limit defines the limiter.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/pmorjan/limit"
	"github.com/tomasen/realip"
)

func main() {

	// middleware function
	limitRequests := func(next http.Handler) http.Handler {
		userLimit, _ := limit.New(1, 3) // 1 request per second, burst 3

		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ip := realip.FromRequest(r)
			if !userLimit.Allowed(ip) {
				http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
				return
			}
			next.ServeHTTP(w, r)
		})
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello world"))
	})

	srv := httptest.NewServer(limitRequests(handler))
	defer srv.Close()

	// 4 requests
	for i := 0; i < 4; i++ {
		res, _ := http.Get(srv.URL)
		fmt.Println(res.Status)
	}

	// next request after 1 sec delay
	time.Sleep(time.Second)
	res, _ := http.Get(srv.URL)
	fmt.Println(res.Status)

}
Output:

200 OK
200 OK
200 OK
429 Too Many Requests
200 OK

func New

func New(rate float64, burst int) (*Limit, error)

New creates a limiter with a "token bucket" of size burst, initially full and refilled at rate per second.

func (*Limit) Allowed

func (l *Limit) Allowed(id string) bool

Allow reports whether an event may happen now.

Jump to

Keyboard shortcuts

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