rate

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2023 License: MIT Imports: 6 Imported by: 0

README

go-rate

Go GitHub tag (latest SemVer) GoDoc Go Report Card Coverage Status

go-rate provides the rate limiters generally.

Features

History

  • v0.5.0

    • BREAK: To decrease unecessary dependants, we removed middleware subpackage. It has been moved into supports/ and taged with ignore.
      • You must copy its codes to use it.
    • the codes reviewed
    • no any third-party deps now, even from mine.
  • v0.1.x

    • as is

Usages

Simple
package main

import (
	"fmt"
	"github.com/hedzr/rate"
	"time"
)

func main() {
	l := rate.New(rate.LeakyBucket, 100, time.Second)
	for i := 0; i < 120; i++ {
		ok := l.Take(1)
		if !ok {
			fmt.Printf("#%d Take() returns not ok, counter: %v\n", i, rate.CountOf(l))
			time.Sleep(50 * time.Millisecond)
		}
	}
}
As a gin middleware
package main

import (
   "github.com/gin-gonic/gin"
   "github.com/hedzr/rate"
   "github.com/hedzr/rate/middleware"
   "time"
)

func webserver() {
	r := engine()
	r.Run(":3000")
}

func engine() *gin.Engine {
	config := &middleware.Config{
		Name:          "...",
		Description:   "...",
		Algorithm:     string(rate.TokenBucket),
		Interval:      time.Second,
		MaxRequests:   1000,
		HeaderKeyName: "X-API-TOKEN",
		ExceptionKeys: nil,
		Routes:        nil,
	}
	r := gin.Default()
	r.Use(middleware.ForGin(config))
	return r
}
Load limit config with cmdr Option Store

While integrated with hedzr/cmdr, the short loading is available:

import "github.com/hedzr/rate/middleware"

func BuildRoutes(rg *gin.Engine) *gin.Engine {
    buildRoutes(rg.Group("/prefix"), rg)
}
func buildRoutes(rg Router, root *gin.Engine) {
    middleware.LoadConfigForGin("server.rate-limits", rg)
    rg.Get("/echo/*action", echoHandler)
}
func echoGinHandler(c *gin.Context) {
    action := c.Param("action")
    if action == "" || action == "/" {
        action = "<no action>"
    }
    _, _ = io.WriteString(c.Writer, fmt.Sprintf("action: %v\n", action))
}

A config file (eg. rate-limit.yml) should be put in cmdr-standard conf.d directory, so it can be loaded automatically:

app:
  your-app: # <- replace it with your app name, the further KB in cmdr docs.
    server:
      rate-limits:
        - name: by-api-key
          interval: 1ms
          max-requests: 30
          header-key-name: X-API-KEY
          exception-keys: [voxr-apps-test-api-key-fndsfjn]

License

MIT

Documentation

Overview

Package rate provides a rate-limiter with a special algorithm.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CountOf

func CountOf(limiter rateapi.Limiter) int64

CountOf extracts the Available tokens/rate-remains count from a rate-limiter

func New

func New(algorithm Algorithm, maxCount int64, d time.Duration) rateapi.Limiter

New returns a new instance of the rate limiter with certain a algorithm.

a nil result means the algorithm of yours has not been registered, so you might:

- use a right algorithm name such as rate.LeakyBucket, rate.TokenBucket - or register yours implement with rate.Register and assign it by algorithm name.

func Register

func Register(algorithm string, generator func(maxCount int64, d time.Duration) rateapi.Limiter) error

Register puts your generator into registry so it will be assign from New() in the future

func Unregister

func Unregister(algorithm Algorithm)

Unregister deregister a limiter generator by algorithm name.

Types

type Algorithm

type Algorithm string

Algorithm represents the rate limit algorithm specifically

const (
	// Counter algorithm
	Counter Algorithm = "counter"
	// LeakyBucket algorithm
	LeakyBucket Algorithm = "leaky-bucket"
	// TokenBucket algorithm
	TokenBucket Algorithm = "token-bucket"
)

Directories

Path Synopsis
_examples
Package counter implements counter algorithm
Package counter implements counter algorithm
internal
Package leakybucket implements leaky-bucket algorithm
Package leakybucket implements leaky-bucket algorithm
pkg
logger
package logger is a minimal logger weapper
package logger is a minimal logger weapper
Package rateapi provides the basic interfaces of hedzr/rate packages.
Package rateapi provides the basic interfaces of hedzr/rate packages.
Package tokenbucket implements token-bucket algorithm
Package tokenbucket implements token-bucket algorithm

Jump to

Keyboard shortcuts

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