tollbooth

package module
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2017 License: MIT Imports: 7 Imported by: 0 modules, 0 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.

README

GoDoc license

Tollbooth

This is a generic middleware to rate-limit HTTP requests.

NOTE 1: This library is considered finished.

NOTE 2: In the coming weeks, I will be removing thirdparty modules and moving them to their own dedicated repos.

NOTE 3: Major version changes are backward-incompatible. v2.0.0 streamlines the ugliness of the old API. Totally not backward-compatible.

Five Minutes Tutorial

package main

import (
    "github.com/didip/tollbooth"
    "net/http"
    "time"
)

func HelloHandler(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("Hello, World!"))
}

func main() {
    // Create a request limiter per handler.
    http.Handle("/", tollbooth.LimitFuncHandler(tollbooth.NewLimiter(1, time.Second, nil), HelloHandler))
    http.ListenAndServe(":12345", nil)
}

Features

  1. Rate-limit by request's remote IP, path, methods, custom headers, & basic auth usernames.

    import "github.com/didip/tollbooth/limiter"
    
    lmt := tollbooth.NewLimiter(1, time.Second, nil)
    
    // or create a limiter with expirable token buckets
    // This setting means:
    // create a 1 request/second limiter and
    // every token bucket in it will expire 1 hour after it was initially set.
    lmt = tollbooth.NewLimiter(1, time.Second, &limiter.TokenBucketOptions{DefaultExpirationTTL: time.Hour})
    
    // Configure list of places to look for IP address.
    // By default it's: "RemoteAddr", "X-Forwarded-For", "X-Real-IP"
    // If your application is behind a proxy, set "X-Forwarded-For" first.
    lmt.SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"})
    
    // Limit only GET and POST requests.
    lmt.SetMethods([]string{"GET", "POST"})
    
    // Limit based on basic auth usernames.
    // You can first define them on-load.
    lmt.SetBasicAuthUsers([]string{"bob", "jane", "didip", "vip"})
    // But you can also add them later.
    lmt.AddBasicAuthUsers([]string{"sansa"})
    // As well as removing them later.
    lmt.RemoveBasicAuthUsers([]string{"vip"})
    
    // Limit request headers containing certain values.
    // You can first define them on-load.
    lmt.SetHeader("X-Access-Token", []string{"abc123", "xyz098"})
    // You can remove it.
    lmt.RemoveHeader("X-Access-Token")
    // You can add new entries on a particular header.
    lmt.AddHeaderEntries("X-Dragons", []string{"drogon", "viserion", "rhaegal"})
    // As well as removing them later.
    lmt.RemoveHeaderEntries("X-Dragons", []string{"viserion"})
    
    // By the way, the setters are chainable. Example:
    lmt.SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}).
        SetMethods([]string{"GET", "POST"}).
        AddBasicAuthUsers([]string{"sansa"}).
        AddBasicAuthUsers([]string{"tyrion"})
    
  2. Each request handler can be rate-limited individually.

  3. Compose your own middleware by using LimitByKeys().

  4. Customize your own message or function when limit is reached.

    import "github.com/didip/tollbooth/limiter"
    
    lmt := tollbooth.NewLimiter(1, time.Second, nil)
    
    // Set a custom message.
    lmt.SetMessage("You have reached maximum request limit.")
    
    // Set a custom content-type.
    lmt.SetMessageContentType("text/plain; charset=utf-8")
    
    // Set a custom function for rejection.
    lmt.SetRejectFunc(func() { fmt.Println("A request was rejected") })
    
  5. Tollbooth does not require external storage since it uses an algorithm called Token Bucket (Go library: golang.org/x/time/rate).

Other Web Frameworks

Sometimes, other frameworks require a little bit of shim to use Tollbooth. These shims below are contributed by the community, so I make no promises on how well they work. The one I am familiar with are: Chi, Gin, and Negroni.

Documentation

Overview

Package tollbooth provides rate-limiting logic to HTTP request handler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildKeys

func BuildKeys(limiter *limiter.Limiter, r *http.Request) [][]string

BuildKeys generates a slice of keys to rate-limit by given limiter and request structs.

func LimitByKeys

func LimitByKeys(limiter *limiter.Limiter, keys []string) *errors.HTTPError

LimitByKeys keeps track number of request made by keys separated by pipe. It returns HTTPError when limit is exceeded.

func LimitByKeysWithTokenBucketTTL

func LimitByKeysWithTokenBucketTTL(limiter *limiter.Limiter, keys []string, bucketExpireTTL time.Duration) *errors.HTTPError

LimitByKeysWithTokenBucketTTL functions just like LimitByKeys. But user can define a TTL for the token bucket to expire. This is to ensure that the middleware won't leak memory. It returns HTTPError when limit is exceeded.

func LimitByRequest

func LimitByRequest(limiter *limiter.Limiter, r *http.Request) *errors.HTTPError

LimitByRequest builds keys based on http.Request struct, loops through all the keys, and check if any one of them returns HTTPError.

func LimitFuncHandler

func LimitFuncHandler(lmt *limiter.Limiter, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler

LimitFuncHandler is a middleware that performs rate-limiting given request handler function.

func LimitHandler

func LimitHandler(lmt *limiter.Limiter, next http.Handler) http.Handler

LimitHandler is a middleware that performs rate-limiting given http.Handler struct.

func NewLimiter

func NewLimiter(max int64, ttl time.Duration, tbOptions *limiter.TokenBucketOptions) *limiter.Limiter

NewLimiter is a convenience function to limiter.New.

func SetResponseHeaders

func SetResponseHeaders(lmt *limiter.Limiter, w http.ResponseWriter)

SetResponseHeaders configures X-Rate-Limit-Limit and X-Rate-Limit-Duration

Types

This section is empty.

Directories

Path Synopsis
Package errors provide data structure for errors.
Package errors provide data structure for errors.
Package libstring provides various string related functions.
Package libstring provides various string related functions.
Package limiter provides data structure to configure rate-limiter.
Package limiter provides data structure to configure rate-limiter.

Jump to

Keyboard shortcuts

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