Learn how to implement rate limiting for requests in Gin using Go. This guide provides a simple example to help you secure your application from abuse and control traffic effectively.
Go, Gin, rate limiting, API requests, traffic control, web application security
// main.go
package main
import (
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
"net/http"
"sync"
"time"
)
// Rate limiter structure
type Limiter struct {
mu sync.Mutex
visitors map[string]*rate.Limiter
}
var limiter = Limiter{visitors: make(map[string]*rate.Limiter)}
// Middleware to limit requests
func RateLimit() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
limiter.mu.Lock()
lim, exists := limiter.visitors[ip]
if !exists {
lim = rate.NewLimiter(1, 3) // Allow 1 request per second with a burst of 3
limiter.visitors[ip] = lim
}
limiter.mu.Unlock()
if !lim.Allow() {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many requests"})
c.Abort()
return
}
c.Next()
}
}
func main() {
router := gin.Default()
router.Use(RateLimit())
router.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello, World!"})
})
router.Run(":8080")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?