Skip to content

yangxikun/gin-limit-by-key

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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")
}

About

A gin middleware to limit access rate by custom key

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages