ratelimiter

package module
v0.0.0-...-cbba30a Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2020 License: Apache-2.0 Imports: 2 Imported by: 0

README

(go) ratelimiter

Sample rate limiter for go HTTP services. This a simple implementation that has not been tested in a production environment and is meant to illustrate the concept.

See examples/sample-ratelimiter.go for a demonstration

How to use this:

  • Build an HTTP router that incorporates the rate limiter:
type SampleRouter struct{
   	throttler map[string]ratelimiter.RateLimit
   }
  • Then, implement a function to use the rate limiter:
	// Check if we should limit/block the connection attempt
	host := strings.Split(request.RemoteAddr, ":")[0]
	if sr.dosShield(host){
		writer.WriteHeader(http.StatusTooManyRequests)
		writer.Write([]byte(`{"message": "Rate limit exceeded"}`))
		return
	}
//
// leverages the rate limiter to check if DOS is suspected
func (sr *SampleRouter) dosShield(host string) bool{
	// Ensure we have an entry for the host if it doesn't already exist
	if _, exists := sr.throttler[host]; !exists{
		limiter := ratelimiter.RateLimit{}
		limiter.Init(15, 65)
		sr.throttler[host] = limiter
	}

	hostLimit := sr.throttler[host]				// Get the throttler for this host
	isRateLimited := hostLimit.IsRateLimited()	// Records the access attempt and checks if this connection should be throttled
	sr.throttler[host] = hostLimit				// Re-assign the RateLimiter to record the updated access attempt
	return isRateLimited
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RateLimit

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

Per-identifier access tracking

Originally designed with rate-limiting calls to go HTTP services

func (*RateLimit) Init

func (rl *RateLimit) Init(maxAttempts int, checkIntervalSec int)

Configure monitoring interval and max access attempts in the interval

func (*RateLimit) IsRateLimited

func (rl *RateLimit) IsRateLimited() bool

Return true if a host/identifier should be rate limited

false is returned if the target identifier/host should not be rate limited

func (*RateLimit) SetIdentifier

func (rl *RateLimit) SetIdentifier(id string)

Set the identifier for this rate limit instance Originally designed to be the IP address of hosts making HTTP connections

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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