How do I rate limit requests with Gin in Go?

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

Go Gin rate limiting API requests traffic control web application security