quota

package
v0.0.0-...-fd9b66f Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2019 License: Apache-2.0 Imports: 5 Imported by: 0

README

API Rate / Quota Limiter Middleware

This package provides a simple and minimalist implementation of API rate / quota request limiter within a http middleware.

How To Use

  1. Implement APIQuotaInterface in your package

    type APIQuotaInterface interface {
        // Parse token from http request.
        ParseTokenFromRequest(ctx context.Context, r *http.Request) (string, error)
        // Check current token's quota plan.
        GetTokenQuotaPlan(ctx context.Context, token string) (int64, error)
    }
    
  2. Initiate package (as singleton)

    type APIQuotaOption struct {
        KeyPrefix string
        Cache     *redis.Pool
        Logger    *logrus.Logger
        Interface APIQuotaInterface
    }
    
    // Call this once.
    quota.Init(APIQuotaOption{
        KeyPrefix: "foo",
        Cache:     cachePool,
        Logger:    logrus.New(),
        Interface: customAPIQuotaImplementation{}, // Use struct defined from 1st step.
    })
    

NOTE

  • Ideally GetTokenQuotaPlan is implemented by selecting into a database.
  • Expiration / validity of the API token should be managed yourself (i.e. create custom cron to set / expire tokens).

Example

Example can be found in the test file: quota_test.go.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CacheKey

func CacheKey(token string) string

Get cache key name on given api key.

func HTTPMiddleware

func HTTPMiddleware(next http.HandlerFunc) http.HandlerFunc

HTTP Middleware for api quota request limiter.

func Init

func Init(opt APIQuotaOption)

Initiate package's variables and dependencies.

Types

type APIQuotaInterface

type APIQuotaInterface interface {
	// Parse token from http request.
	ParseTokenFromRequest(ctx context.Context, r *http.Request) (string, error)
	// Check current token's quota plan.
	GetTokenQuotaPlan(ctx context.Context, token string) (int64, error)
}

API Quota middleware interface definition.

type APIQuotaOption

type APIQuotaOption struct {
	KeyPrefix string
	Cache     *redis.Pool
	Logger    *logrus.Logger
	Interface APIQuotaInterface
}

API Quota middleware package initiation options.

Jump to

Keyboard shortcuts

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