limit

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

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

Go to latest
Published: May 12, 2019 License: MIT Imports: 4 Imported by: 6

README

Description

An in-memory Gin middleware to limit access rate by custom key and rate.

It depends on two library:

installation

go get -u github.com/yangxikun/gin-limit-by-key

Example

package main

import (
    limit "github.com/yangxikun/gin-limit-by-key"
    "github.com/gin-gonic/gin"
    "golang.org/x/time/rate"
)

func main() {
	r := gin.Default()

	r.Use(limit.NewRateLimiter(func(c *gin.Context) string {
		return c.ClientIP() // limit rate by client ip
	}, func(c *gin.Context) (*rate.Limiter, time.Duration) {
		return rate.NewLimiter(rate.Every(100*time.Millisecond), 10), time.Hour // limit 10 qps/clientIp and permit bursts of at most 10 tokens, and the limiter liveness time duration is 1 hour
	}, func(c *gin.Context) {
		c.AbortWithStatus(429) // handle exceed rate limit request
	}))

	r.GET("/", func(c *gin.Context) {})

	r.Run(":8888")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewRateLimiter

func NewRateLimiter(key func(*gin.Context) string, createLimiter func(*gin.Context) (*rate.Limiter, time.Duration),
	abort func(*gin.Context)) gin.HandlerFunc

Types

This section is empty.

Jump to

Keyboard shortcuts

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