httprl

package module
v0.0.0-...-20dc802 Latest Latest
Warning

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

Go to latest
Published: May 5, 2016 License: BSD-3-Clause Imports: 7 Imported by: 42

README

httprl

GoDoc GoReportCard

Package httprl provides a rate limiter for http servers.

Documentation

Overview

Package httprl provides a rate limiter for http servers.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrLimitExceeded      = errors.New("Rate limit exceeded")
	ErrServiceUnavailable = errors.New("Service unavailable, try again later")
)

Errors.

View Source
var DefaultKeyMaker = func(r *http.Request) string {
	addr, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return addr
}

DefaultKeyMaker is a KeyMaker that returns the client IP address from the request, without the port.

Functions

This section is empty.

Types

type Backend

type Backend interface {
	// Hit tells the backend that a given key has been hit, and
	// if it does not exist in the backend, should be set to 1
	// with the given time-to-live, in seconds. Returns the
	// hit count and remaining ttl for the given key.
	Hit(key string, ttlsec int32) (count uint64, remttl int32, err error)
}

Backend defines an interface for rate limiters. It can be implemented by in-memory caches such as redis and memcache.

type KeyMaker

type KeyMaker func(r *http.Request) string

A KeyMaker makes keys from the http.Request object to the RateLimiter.

type Map

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

Map is a rate limiter implementation using a map and goroutine to expire keys.

Example
package main

import (
	"io"
	"net/http"

	"github.com/go-web/httprl"
)

func myHandler(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Hello, world")
}

func main() {
	rl := &httprl.RateLimiter{
		Backend:  httprl.NewMap(1),
		Limit:    5,
		Interval: 1,
		KeyMaker: func(r *http.Request) string {
			return r.Header.Get("X-Auth-Token")
		},
	}
	mux := http.NewServeMux()
	mux.Handle("/", rl.HandleFunc(myHandler))
	http.ListenAndServe(":8080", mux)
}
Output:

func NewMap

func NewMap(precision int32) *Map

NewMap creates and initializes a new Map. The precision determines how often the map is scanned for expired keys, in seconds.

func (*Map) Hit

func (m *Map) Hit(key string, ttlsec int32) (count uint64, remttl int32, err error)

Hit implements the httprl.Backend interface.

func (*Map) Start

func (m *Map) Start()

Start starts the internal goroutine that scans the map for expired keys and remove them.

func (*Map) Stop

func (m *Map) Stop()

Stop stops the internal goroutine started by Start.

type Policy

type Policy int

Policy defines the rate limiter policy to apply when the backend fails.

const (
	// BlockPolicy blocks requests when backend is unavailable.
	BlockPolicy Policy = iota
	// AllowPolicy allows requests when backend is unavailable.
	AllowPolicy
)

type RateLimiter

type RateLimiter struct {
	Backend                Backend          // Backend for the rate limiter
	Limit                  uint64           // Maximum number of requests per interval
	Interval               int32            // Interval in seconds
	KeyMaker               KeyMaker         // Function to generate a key from the request (DefaultKeyMaker)
	Policy                 Policy           // Policy when backend fails (default BlockPolicy)
	ErrorLog               *log.Logger      // Optional logger for backend errors (optional)
	LimitExceededFunc      http.HandlerFunc // Function called when limit exceeded (optional)
	ServiceUnavailableFunc http.HandlerFunc // Function called when backend is unavailable (optional)
}

A RateLimiter is an http.Handler that wraps another handler, and calls it up to a certain limit, per time interval.

func (*RateLimiter) Handle

func (rl *RateLimiter) Handle(next http.Handler) http.Handler

Handle handles incoming requests by applying rate limit, and calls f.ServeHTTP if the client is under the limit.

func (*RateLimiter) HandleFunc

func (rl *RateLimiter) HandleFunc(f http.HandlerFunc) http.HandlerFunc

HandleFunc handles incoming requests by applying rate limit, and calls f if the client is under the limit.

Directories

Path Synopsis
Package memcacherl is a memcache client wrapper for rate limiting.
Package memcacherl is a memcache client wrapper for rate limiting.
Package redisrl is a redis client wrapper for rate limiting.
Package redisrl is a redis client wrapper for rate limiting.

Jump to

Keyboard shortcuts

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