Skip to content

Gin middleware

Use the Gin adapter as a global or route-group middleware.

Prerequisites

  • Go 1.24 or newer
  • port 8080 available

Run

go run ./examples/gin
examples/gin/main.go
// Package main demonstrates using GoRL with the Gin middleware.
package main

import (
    "log"
    "net/http"
    "time"

    "github.com/AliRizaAynaci/gorl/v2"
    "github.com/AliRizaAynaci/gorl/v2/core"
    ginmw "github.com/AliRizaAynaci/gorl/v2/middleware/gin"
    "github.com/gin-gonic/gin"
)

func main() {
    limiter, err := gorl.New(core.Config{
        Strategy: core.SlidingWindow,
        Limit:    5,
        Window:   30 * time.Second,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer limiter.Close()

    r := gin.Default()
    r.Use(ginmw.RateLimit(limiter))

    r.GET("/", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "Hello from Gin!"})
    })

    r.Run(":8080")
}
for i in 1 2 3 4 5 6; do curl -i http://localhost:8080/; done

Expected behavior

Gin uses ClientIP() as the default key. Five requests are allowed per thirty- second sliding window; the next request receives a JSON 429 response.

Production cautions

Configure Gin's trusted proxies to match the deployment, and consider a custom key based on authenticated client identity. For resource-scoped middleware, GoRL prefers FullPath() so parameterized routes share the intended policy.