-
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
86 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package middleware | ||
|
||
import ( | ||
"time" | ||
|
||
"github.com/gofiber/fiber/v2" | ||
"github.com/gofiber/fiber/v2/middleware/limiter" | ||
) | ||
|
||
// RateLimiterConfig default rate limiter configuration | ||
var RateLimiterConfig = limiter.Config{ | ||
Max: 100, // Maximum number of requests per duration | ||
Expiration: 1 * time.Minute, // Duration for rate limit window | ||
KeyGenerator: func(c *fiber.Ctx) string { | ||
return c.IP() // Use client IP as key | ||
}, | ||
LimitReached: func(c *fiber.Ctx) error { | ||
return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{ | ||
"status": false, | ||
"message": "Rate limit exceeded. Please try again later.", | ||
}) | ||
}, | ||
SkipFailedRequests: false, // Count failed requests | ||
SkipSuccessfulRequests: false, // Count successful requests | ||
} | ||
|
||
// NewRateLimiter creates a new rate limiter middleware with custom config | ||
func NewRateLimiter(max int, duration time.Duration) fiber.Handler { | ||
config := RateLimiterConfig | ||
config.Max = max | ||
config.Expiration = duration | ||
return limiter.New(config) | ||
} | ||
|
||
// DefaultRateLimiter creates a rate limiter with default configuration | ||
func DefaultRateLimiter() fiber.Handler { | ||
return limiter.New(RateLimiterConfig) | ||
} |