GinRateLimit

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2021 License: MIT Imports: 3 Imported by: 0

README

GinRateLimit

GinRateLimit is a rate limiter for the gin framework. By default, it can only store rate limit info in memory. If you want to store it somewhere else like redis you can make your own store or use third party stores, similar to how express-rate-limit does it. The library is new so there are no third party stores yet, so I would appreciate if someone could make one.

Install

go get github.com/Nebulizer1213/GinRateLimit

Basic Setup

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/Nebulizer1213/GinRateLimit"
)

func keyFunc(c *gin.Context) string {
	return c.ClientIP()
}

func errorHandler(c *gin.Context) {
	c.String(429, "Too many requests")
}

func main() {
	server := gin.Default()
	// This makes it so each ip can only make 5 requests per second
	store := GinRateLimit.InMemoryStore(1, 5)
	mw := GinRateLimit.RateLimiter(keyFunc, errorHandler, store)
	server.GET("/", mw, func(c *gin.Context) {
		c.String(200, "Hello World")
	})
	server.Run(":8080")
}

Custom Store Example

package main

type CustomStore struct {
}

// Your store must have a method called Limit that takes a key and returns a bool
func (s *CustomStore) Limit(key string) bool {
	// Do your rate limit logic, and return true if the user went over the rate limit, otherwise return false
	if UserWentOverLimit {
		return true
	}
	return false
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RateLimiter

func RateLimiter(keyFunc func(c *gin.Context) string, errorHandler func(c *gin.Context), s store) func(ctx *gin.Context)

Types

type InMemoryStoreType

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

func InMemoryStore

func InMemoryStore(rate int, limit int) *InMemoryStoreType

func (*InMemoryStoreType) Limit

func (s *InMemoryStoreType) Limit(key string) bool

Jump to

Keyboard shortcuts

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